What is the use of Arrow Function?

What is the use of Arrow Function?

Let’s take a look at the example to understand the use case of Arrow function:

Example :

var ScoreCard = function () {
    this.score = 0;

    this.getScore = function () {
        setTimeout(function () {
            console.log(this.score);    // gives undefined.    
        }, 1000);
    }    
}

var a = new ScoreCard();
a.getScore();

You have created an anonymous function which has a property this. Score initialize to 0 and a method getScore which internally has a setTimeout, and in 1 second it consoles this.score. The consoled value gives undefined though you have this.score defined and initialized. The issue here is with this keyword. The function inside setTimeout has its own this, and it tries to refer the score internally, and since it is not defined, it gives undefined.

The same can be taken care using Arrow function as shown below:

var ScoreCard = function () {
    this.score = 0;

    this.getScore = function () {
        setTimeout(()=>{
            console.log(this.score);   // you get  0
        }, 1000);
    }    
}

var a = new ScoreCard();
a.getScore();

You have changed the function inside setTimeout to a arrow function as shown below:

setTimeout(()=>{
            console.log(this.score);   // you get  0
        }, 1000);

An arrow function does not have its own this defined and it shares its parent this, so variables declared outside are easily accessible using this inside an arrow function. They are useful because of the shorter syntax as well as for callbacks, event handlers, inside timing functions, etc.

About Author

Leave a Reply

Your email address will not be published. Required fields are marked *

PAGE TOP
error

Enjoy this blog? Please spread the word :)

RSS
Follow by Email