Beginning in ES6 : Arrow Functions =>

Sukhmeet Singh
2 min readAug 2, 2016

--

ES6(ECMAScript 6) is gaining a lot of traction and new function declaration or fat-arrow => notation is one of the most popular ones. Lets try to understand it what it is all about and how it is different from ES5.

Syntax:

// ES5 
function(param1, param2, .... paramN){ return expression}
// ES6
(param1, param2, .... paramN) => { return expression}

In the first look it is easily noticeable that the keyword ‘function’ is replaced by big-fat-arrow =>. It does the same thing, so now we write less of code when defining functions.

Lets look at some examples how this is done

There is one other important aspect of => functions which is binding the context of ‘this’ . This has been an issue for a lot of time in ES5 version of javascript and leads to erroneous situations. Lets look at what exactly is the issue -

Lets understand why in the first case ‘this.name’ was undefined. The reason is — ‘this’ always refers to the owner of the function it is called by.

In our case object’s function (in this case printTasks) is in the scope of the object(player) and hence ‘this’ refers to the object(player)and we access this.tasks .
On the other hand in ‘forEach’ loop we create an anonymous inner function closure which cannot access the ‘this’ from the outer function and there is no explicit ‘this’ passed to it. Therefore it refers to global window as ‘this’ here. Therefore the value ‘name’ prints as undefined.(or prints value of window.name)

ES5 has ways to fix this problem as demonstrated. Fix-1 is the most common solution. In Fix-2 we use native ‘bind’ method and in Fix-3 we explicitly pass the context of ‘this’ to forEach loop as a second argument.

ES6 arrow functions solves this problem . With => functions the ‘this’ inside the function refers to current surrounding scope. So we need not worry about it.

This works as expected.

Syntax quirks

There are also couple of things to note with respect to syntax .

  1. => functions can’t be used as a constructor functions. Hence writing ‘new’ before it, will throw an error .
new ()=>{}  // invalid
new (()=>{}) // invalid

2) Line break after arrow function parameters is invalid .But inside parameter definition it is valid.

Thats it, thats all in the world of ES6 => functions. So next time, you see a function keyword , try reducing it to ES6 => .

Further Reading

  1. http://javascriptissexy.com/understand-javascripts-this-with-clarity-and-master-it/
  2. https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Functions/Arrow_functions
  3. http://exploringjs.com/es6/ch_arrow-functions.html
  4. https://ponyfoo.com/articles/es6-arrow-functions-in-depth

--

--