Why Arrow Function?

pratham0182

Prathamesh Patil

Posted on February 3, 2020

Why Arrow Function?

Before knowing why to go with arrow functions. let us know what is arrow functions. Below is an example of normal function

//Normal Function

myfunction(){
    return 'I am a Normal Function';
}

Enter fullscreen mode Exit fullscreen mode

Now We can write the above function in arrow function as shown below


//Arrow Function

const myfunction = ()=>{
    return 'I am Arrow Function';
}

Enter fullscreen mode Exit fullscreen mode

Suppose we want to send parameter in an arrow function then we can pass as


const myfunction = (name,age)=>{
    return 'My Name is'+name+','+age+'years old';
}


Enter fullscreen mode Exit fullscreen mode

Now if we have a single parameter to pass then we can also write the function as


const myfunction = name =>{
    return 'My Name is'+name+','+age+'years old';
}

Enter fullscreen mode Exit fullscreen mode

Now the question is why this arrow function what's the use of arrow functions.
Let's take an example we have a class person which as a function personName() which in return console logs the name with a delay of 100 ms.

class Person{

constructor(name){
   this.name = name;
}

personName(){
    return setTimeout(function(){

        console.log('Name is '+this.name);
    },100);
}
}

per =new Person('Peter');

per.person();

//Output 'Name is Undefined';

Enter fullscreen mode Exit fullscreen mode

So the output is not what we expected .. this says that this is now no more accessible in inner functions.
To solve this there is a solution we can simply bind this function to current objects as


personName(){
    return setTimeout(function(){

        console.log('Name is '+this.name);
    }.bind(this),100);
}

****OR****

personName(){

    var that = this;
    return setTimeout(function(){

        console.log('Name is '+that.name);
    },100);
}

Enter fullscreen mode Exit fullscreen mode

But this solution doesn't seem to a good solution ... so to solve this javascript came with an arrow function which knows from which context it has been called.
Below code shows that now this is accessible in the inner function

class Person{

constructor(name){
   this.name = name;
}

personName(){
    return setTimeout(()=>{

        console.log('Name is '+this.name);
    },100);
}
}

per =new Person('Peter');

per.person();

//Output 'Name is Peter';

Enter fullscreen mode Exit fullscreen mode
💖 💪 🙅 🚩
pratham0182
Prathamesh Patil

Posted on February 3, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related