Arrow Functions in Es 6

Es 6 has introduced new Arrow function. Let's first illustrate what an arrow function looks like, as compared to normal functions:
function foo(x,y) {
    return x + y;
}

// versus

var foo = (x,y) => x + y;
The arrow function definition consists of a parameter list (of zero or more parameters, and surrounding ( .. ) if there's not exactly one parameter), followed by the => marker, followed by a function body.
So, in the previous snippet, the arrow function is just the (x,y) => x + y part, and that function reference happens to be assigned to the variable foo.
The body only needs to be enclosed by { .. } if there's more than one expression, or if the body consists of a non-expression statement. If there's only one expression, and you omit the surrounding { .. }, there's an implied return in front of the expression, as illustrated in the previous snippet.
Arrow functions are always function expressions; there is no arrow function declaration. It also should be clear that they are anonymous function expressions -- they have no named reference for the purposes of recursion or event binding/unbinding.
A simple short arrow function example as follow:
var a = [1,2,3,4,5];

a = a.map( v => v * 2 );

console.log( a );               // [2,4,6,8,10]
Arrow functions alter
this
behavior in a specific way. Lets see it with an example, Fiddle
var controller = {
    makeRequest: function(){
        var btn=document.getElementById("btn");
        btn.addEventListener( "click", function(){
            console.log(this);
            
        }, false );
    }
};

controller.makeRequest();
In the above snippet `this` is accessing the scope of HTMLButtonElement, Arrow function will alter this, Lets see it in the action here

Share this post