Javascript ES6 arrow function
Arrow function also known as flat arrows are more shorter compare to functions. Lets have a look at it.
Here is a function written in ES5 syntax:
function add(a,b) {
return a + b
}
add(1,3) //3
Es6 function
const add = (a,b) => a+b
const value = a => console.log(a)
value(1) // 1
It’s much shorter compare to above code. We are able to omit the curly braces and the return statement due to implicit returns.
In classic function expressions, the this
keyword is bound to different values based on the context in which it is called. With arrow functions however, this
is lexically bound. It means that it usesthis
from the code that contains the arrow function.
// ES5
var obj = {
id: 1,
counter: function counter() {
setTimeout(function() {
console.log(this.id);
}.bind(this), 1000);
}
};
In the ES5 example, .bind(this)
is required to help pass the this
context into the function. Otherwise, by default this
would be undefined.
// ES6
var obj = {
id: 1,
counter: function counter() {
setTimeout(() => {
console.log(this.id);
}, 1000);
}
};
ES6 arrow functions can’t be bound to a this
keyword, so it will lexically go up a scope, and use the value of this
in the scope in which it was defined.
Conclusions
In this post, you learned about Javascript ES6 and its comparison with ES5 function.