Why Arrow Function?
Prathamesh Patil
Posted on February 3, 2020
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';
}
Now We can write the above function in arrow function as shown below
//Arrow Function
const myfunction = ()=>{
return 'I am Arrow Function';
}
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';
}
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';
}
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';
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);
}
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';
Posted on February 3, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.