ECMAScript 6 provides a new way to create functions which just contain one line of statement. This new type of function is called lambda or arrow function.
Here is how to create a arrow function
//x and y are function parameters
var sum = (x, y) => x + y;
console.log(sum(2, 900)); //902
Here (x, y) => x + y
returns a regular JavaScript function object. Here the function body of the returned function object’s body would be function(x, y){return x+ y;}
Arrow functions always return the value of the statement when executed. Here result of x+y
is returned.
You can also write multiple statements in an arrow function but arrow functions are mostly used in replacement of single statement functions. Here is code example of multiple statements in an arrow function
x = x + 10;
y = y + 10;
return x + y;
}
console.log(sum(10, 10)); //40
As arrow function actually returns a regular JavaScript function object so they can be used wherever we use regular JavaScript function object. For example, they can be used as callback.
{
console.log(p() + q()); //87
}
sum(a => 20 + 10, b => 1 + 56); //here we are passing two function objects
One last and most important feature about arrow function is that the “this” pointer inside an asynchronously executed arrow function points to the scope inside which it was passed as callback. A regular function’s this pointer points to global scope when executed asynchronously.
function Person(){
this.age = 34;
setTimeout(() => {
console.log(this.age); //34
}, 1000);
setTimeout(function(){
console.log(this.age); //12
}, 1000);
}
var p = new Person();
Leave a Reply