An arrow function is short function expression, used to replace with regular function in low complexity. Arrow functions were introduced to JavaScript in ES6.
The intention to create arrow function is to shorten function code. Arrow function has its advantage and disadvanatges comparing with normal function.
First of all, lets see how normal function looks in the examples:
// normal function to sum 2 numbers
function addition(a + b) {
return a + b;
}
Now lets see how it is written in arrow function. In arrow function, there is no function keyword.
var addition = (a + b) => {
return a + b;
}
Even, if function has only one statement and it return a value, You don't even need to write return keyword.
var addition = (a + b) => a + b;
If there is only one parameter in the function, brackets can be removed.
var getDouble = a => a * 2;
There is limitation for arrow functions:
Arrow function doesn't have own bindings of this
keyword.
Arrow function not be used as constructors.
Arrow functions are harder to read compare to normal functions.
However arrow functions are best to apply on callbacks as arrow functions are anonymous. Arrow functions are also good in methods like map
or reduce
.