What is an arrow function and why use arrow function in JavaScript?

What is arrow function in JavaScript?

Arrow function is an alternative of regular function expression with a very clean concise syntax. Arrow functions are name-less, this-less, arguments-less, new.target-less, super-less, function keyword less, return keyword less.

Example of arrow function

Here is a basic example of arrow function:

() => console.log("Hello World");

To execute the above function we can do this:

(() => console.log("Hello World"))();

Arrow function as callback

var numbers =[78, 32, 52];
console.log(numbers.filter(number => number > 33));
// The callback of filter function is an arrow function

Why arrow function in JavaScript?

Lets consider the following example:

function getName(rank) {
    this.rank = rank;
}

getName.prototype.addRank = function (arr) {
    return arr.map(function (item) {
        return this.rank + item; // this.rank is undefined here
    });
};

Explanation
On the code we have declared a addRank method to the function prototype of getName method. So, inside the addRank method the special object this is set from getName method.

But when we have started a map method, it has a callback function with a different special object this. Inside the map callback function this.rank is not available. How do we solve this?

By storing “this” to another local variable

function getName(rank) {
    this.rank = rank;
}

getName.prototype.addRank = function (arr) {
    var self = this;
    return arr.map(function (item) {
        return self.rank + item;
    });
};

By passing “this” with map function

function getName(rank) {
    this.rank = rank;
}

getName.prototype.addRank = function (arr) {
    return arr.map(function (item) {
        return this.rank + item;
    }, this);
};

By binding “this” with map function

function getName(rank) {
    this.rank = rank;
}

getName.prototype.addRank = function (arr) {
    return arr.map(function (item) {
        return this.rank + item;
    }.bind(this));
};

Using concise ES6 arrow functions

function getName(rank) {
    this.rank = rank;
}

getName.prototype.addRank = function (arr) {
    return arr.map(item => this.rank + item);
};

Explanation
To solve these kind of issues JavaScript introduced ES6 arrow functions. The arrow function does not have it’s own special object this. If the special object this is used inside arrow function then the enclosing lexical scope is used.

The enclosing lexical scope for the callback of map function is the scope of addRank method. Inside the addRank method, the special object this.rank is available. That’s how it gets the value for rank.