Arrow functions in JavaScript(ES6)
The 2015 edition of the ECMAScript specification aka (ES6) added arrow functions to the JavaScript language. But arrow functions can’t perform some of the functionalities like the traditional functions and they can’t be used in some situations. If you are leaning JavaScript and just want an idea about arrow functions this article is for you.
This is a new and very easy way of writing anonymous functions in a JavaScript.
This example will help you to understand the difference between normal function and a arrow function.
This is the traditional way of writing functions
first=function(){
return "Hello everybody"
};
and here is the way of writing arrow function.
first=()=>{
return "Hello everybody"
};
As you can see in the examples, the “function” keyword in the traditional function has been replaced by the “( )=>” and the rest, stays the same. Let’s see what can we do with the newly added parts.
“( )” parentheses are for the parameters. If the function have single parameter, you don’t need parentheses. And if the expression is simple, you don’t need brackets and “return” statement.
param a => expression ;
But if you have more than one parameter you’ll need parentheses.
(param a, param b) => expression ;
If the function have multiline statements, you’ll need “return ” statement and the brackets.
(param a, param b) => {
let name="john";
return (name + param a + param b);
} ;
Those are the basics of the JavaScript arrow functions. Arrow function expressions are best suited for non-method functions.
If you have a complete understanding of the above content, that means all you have left to do is, learn some of the constraints of arrow functions. For that refer this article from Mozilla Developer Network.