Arrow functions in ES-6



Code for this and several other ES-6 features can be found in my github

ES-6 introduced a shorthand notation to declare functions. In addition to this being a shorthand and being concise, there are a few other advantages specific to scoping that we will see in the next section.
Let us for example, consider a simple map reduce in Javascript ES-5:

var arr = [1,2,3,4,5];
var result = arr.map(
    function(a) {
        return a+1
    }).reduce(
        function(a,b){    
            return a+b
});
While the same thing can be written in ES-6 in a concise manner as follows:

var arr = [1,2,3,4,5];
var result = arr.map((a)=>a+1).reduce((a,b)=>a+b);
console.log(result);
About the syntax:
ES-6 arrow functions can be declared as constants as follows:

const add = (a,b)=> a+b;
and this function can be passed around or used in a way any other function in JS would be.
It is important to note that, if the function body is a single line there is no need for curly braces around the body. Which is why there are not curly braces around 

a+b;
And by default the result of a+b will be returned implicitly.
However, if the function body has multiple lines of code, for example:

const kindOfAdd = (a,b)=> {
let x = a+1;
let y = b+1;
return x+y;
}
If you see in the function
 kindOfAdd 
, the body has multiple lines. Hence it should be surrounded by curly braces and also the expected return value should be explicitly returned.

Comments

Popular posts from this blog

Docker Commands

Dockerfile

ES-6 classes