Arrow functions in Javascript
Arrow functions are introduced in ES6. This makes code cleaner and brought more clarity in Javascript code.
Function in ES5 version
const square = funtion(number) {
return number * number;
}
Function in ES6 version
/* if there is only a single parameter taken by the function then there is no need of parenthesis*/
const square = number => {
return number * number
}
We can also make it more clear by removing the return keyword
//If there is a single line of code in the function then we can remove return keyword and curly braces
const square = number => number * number;
** This function is equalent to the function which we defined in ES5 format **
Arrow Functions and this keyword
Let's define a function in an object
const person = {
talk(){
console.log('this', this)
}
}
person.talk();
//Output of the above code is a reference to the function
If we keep this keyword in the setTimeout function it returns a window object or undefined
const person = {
talk(){
setTimeout(function(){
console.log('this', this)
}, 1000);
}
}
// Output of the above code returns undefined or window object if there is no strict mode enabled
// To solve this
const person = {
talk() {
var self = this;
setTimeout(function(){
console.log('this', self);
}, 1000);
}
}
//Output of the above code is a reference to the person object
** Same code using the arrow function no need to declare a variable **
const person = {
talk() {
setTimeout(() => {
console.log('this', this);
}, 1000);
}
}
/* Output is
this {talk: f}*/
** The reason is arrow function will inherits the context in which code is defined **