ES6 Arrow Functions in Depth by Ponfoo

In notebook:
Article Notes
Created at:
2016-01-06
Updated:
2016-01-06
Tags:
JavaScript Fundamentals
ES6 Arrow Functions in Depth
ES5:
[1, 2, 3].map(function (num) { return num * 2 })
ES6:
[1, 2, 3].map(num => num * 2)

If there are no arguments or more than one we have to use parenthesis:
[1, 2, 3, 4].map((num, index) => num * 2 + index)

If you don't want immediately return a value you have to add brackets (​{}​):
[1, 2, 3, 4].map(num => {
  var multiplier = 2 + num
  return num * multiplier
})

If you want to return an object literal, you have to wrap it in parenthesis:
[1, 2, 3].map(n => ({ number: n }))
// <- [{ number: 1 }, { number: 2 }, { number: 3 }]

So in most cases it's not that simpler than the old ​function​ syntax, don't use the arrow functions automatically just because it's new and cool. Also anonymous functions make more work for other users of your code and make harder to use stack traces. 

​this​ lexical binding

This is big change compared to how ​this​ was defined in ES5. It's not the call context anyomore that define the ​this​ variable but the containing object. ​.call​ or ​.apply​ wont change the context.