Arrow Functions in JavaScript
Arrow functions are a concise syntax for writing functions in JavaScript, introduced in ES6. They allow for a shorter syntax than traditional function expressions and also provide different behavior for this
.
Syntax:
Arrow functions:
Have a shorter syntax.
Do not bind their own
this
(they inheritthis
from the surrounding scope, making them useful for callbacks).Are always anonymous (you cannot name an arrow function directly).
For one argument there is no need to put ( ) braces
- we did not put n in ( ) braces because there is only one argument
Arrow Function with Implicit Return
If the arrow function consists of a single expression, you can omit the curly braces {}
and the return
statement. This is called implicit return.
Example with Implicit Return:
- In this case, the expression
a + b
is returned automatically, without the need for thereturn
keyword or curly braces.
this
with Regular Functions
In a regular function, the value of this
is determined by how the function is called. If the function is called as a method of an object, this
refers to the object. If the function is called in the global context, this
refers to the global object (e.g., window
in browsers).
Example with Regular Function:
- as we can see here “this” refers to the object person
this
with Arrow Functions
Unlike regular functions, arrow functions do not have their own this
. Instead, they lexically inherit this
from the surrounding (or outer) scope in which they were defined. This means that the value of this
inside an arrow function is determined by the value of this
in the context where the arrow function was created.
Example with Arrow Function:
In this example:
- The arrow function does not bind its own
this
. Instead, it inheritsthis
from the surrounding global scope, wherethis
refers to the global object (in browsers,window
). Sincethis.name
isundefined
in the global object, the output is"Hello, undefined"
.
let student = {
name: "david",
gender: "Male",
Dep: "CSE",
getInfo1: function () {
setTimeout(() => {
console.log(this);
}, 2000);
},
getInfo2: function () {
setTimeout(function () {
console.log(this);
}, 2000);
},
};
student.getInfo1();
student.getInfo2();
- student.getInfo1() refers to the student object because “this” is written inside the arrow function and the “this” of the arrow function refers to the object of its parent block which is the student object
- student.getInfo2() refers to the window object because “this” is called by the setTimeout function and this function is a part of window object.
Subscribe to my newsletter
Read articles from dheeraj koranga directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by