There are two benefits to arrow functions.
- Shorter syntax
=>
compared to function expressions. this
is picked from the lexical scope (also called static scope).
Arrow functions are always anonymous. The examples are below:
Function without any parameters
var intro = () => "Welcome";
The above code is equivalent of the below:
var intro = function intro() {
return "Welcome";
};
Using Arrow function with map
const arr = [1, 2, 3];
const squares = arr.map(x => x * x);
The above code is equivalent of the below:
var arr = [1, 2, 3];
var squares = arr.map(function (x) {
return x * x;
});
Function with 1 parameter
var multiplyBy2 = value1 => value1 * 2;
console.log(multiplyBy2(4)); // prints 8
The above code is equivalent of the below:
var multiplyBy2 = function multiplyBy2(value1) {
return value1 * 2;
};
console.log(multiplyBy2(4)); // prints 8
Function with more than 2 parameters
var add = (value1, value2) => value1 + value2;
console.log(add(10, 20)); // prints 30
The above code is equivalent of the below:
var add = function add(value1, value2) {
return value1 + value2;
};
console.log(add(10, 20)); // prints 30
this reference
The source of this is an important distinguishing aspect of arrow functions:
- Traditional functions have a
dynamic this
; its value is determined by how they are called. - Arrow functions have a
lexical this
; its value is determined by the surrounding scope.
The following variables are all lexical inside arrow functions:
arguments
super
this
new.target
An arrow function does not create its own this context, so this has the original meaning from the enclosing context.
Working with this
until traditional way
function Person() {
var _this = this;
this.count = 0;
setInterval(function () {
console.log(_this.count++); // |this| properly refers to the person object
}, 1000);
}
The above code is equivalent of the below:
function Person(){
this.count = 0;
setInterval(() => {
console.log(this.count++); // |this| properly refers to the person object
}, 1000);
}
Returning object literals
The object literal returned by this arrow function is like below:
const f = x => ({ bar: 123 })
The above code is equivalent of the below:
var f = function f(x) {
return { bar: 123 };
};