2. Arrow Functions
Arrow functions are a short-hand notation for writing functions in ES6. The arrow function definition consists of a parameter list ( ... )
, followed by the =>
marker and a function body. For single-argument functions, the parentheses may be omitted.
// Classical Function Expression
function addition(a, b) {
return a + b;
};
// Implementation with arrow function
const addition = (a, b) => a + b;
// With single argument, no parentheses required
const add5 = a => 5 + a;
Note that in the above example, the addition
arrow function is implemented with “concise body” which does not need an explicit return statement. Note the omitted { }
after the =>
.
Here is an example with the usual “block body.” Including the curly brace wrappers.
const arr = ['apple', 'banana', 'orange'];
const breakfast = arr.map(fruit => {
return fruit + 's';
});
console.log(breakfast); // ['apples', 'bananas', 'oranges']
Behold! There is more…
Arrow functions don’t just make the code shorter. They are closely related to this
binding behavior.
Arrow functions behavior with this
keyword varies from that of normal functions. Each function in JavaScript defines its own this
context but arrow functions capture the this
value of the nearest enclosing context. Check out the following code:
function Person() {
// The Person() constructor defines `this` as an instance of itself.
this.age = 0;
setInterval(function growUp() {
// In non-strict mode, the growUp() function defines `this`
// as the global object, which is different from the `this`
// defined by the Person() constructor.
this.age++;
}, 1000);
}
var p = new Person();
In ECMAScript 3/5, this issue was fixed by assigning the value in this
to a variable that could be closed over.
function Person() {
const self = this;
self.age = 0;
setInterval(function growUp() {
// The callback refers to the `self` variable of which
// the value is the expected object.
self.age++;
}, 1000);
}
As mentioned above, arrow functions capture the this value of the nearest enclosing context, so the following code works as expected, even with nested arrow functions.
function Person() {
this.age = 0;
setInterval(() => {
setTimeout(() => {
this.age++; // `this` properly refers to the person object
}, 1000);
}, 1000);
}
let p = new Person();