Javascript Arrow functions
In ES6, arrow functions were introduced as a shorthand for defining functions in JavaScript. (ECMAScript 2015). Because they use an arrow (=>) to distinguish the function arguments from the function body, they are also referred to as “fat arrow” functions.
Syntax:
(parameters) => { statements }
Here’s an example of an arrow function that takes two parameters and returns their sum:
const sum = (a, b) => { return a + b };
This is equivalent to the following traditional function:
function sum(a, b) {
return a + b;
}
The fact that arrow functions have a shorter syntax than conventional functions is one of their key advantages. For instance, you can eliminate the parenthesis surrounding the argument list if the function only accepts one parameter:
const double = x => { return x * 2 };
This is equivalent to the following traditional function:
function double(x) {
return x * 2;
}
If the function body only consists of a single expression, you can omit the curly braces and the return
keyword. This is known as implicit return:
const triple = x => x * 3;
This is equivalent to the following traditional function:
function triple(x) {
return x * 3;
}
Additionally, arrow functions have a lexical this binding, which allows them to take the this value from the surrounding scope. In contrast to conventional functions, which have a dynamic this binding that changes depending on how the function is invoked, this one does not.
Here is an illustration showing how an arrow function differs from a conventional function with regard to this binding:
const obj = {
name: 'John',
traditional: function() {
console.log(this.name);
},
arrow: () => {
console.log(this.name);
}
};
obj.traditional(); // "John"
obj.arrow(); // undefined
Because it is being called as a method of obj in this case, the conventional function logs the value of this.name, which is obj.name. However, because it inherits the global object’s value from the enclosing scope, the arrow function logs undefined. (or undefined in strict mode).
In general, arrow functions offer a more condensed syntax for writing functions in JavaScript, but they also behave differently from conventional functions, especially with regard to this binding.