ES6 Arrows

ES6 makes functions a lot nicer. You can now create functions that look like this:

const cats = () => {
  return 'are awesome'
}

When there is only one line you get implicit returns. It looks like this:

const cats = () => "are awesome"

this made sane

The biggest benefit of arrow functions is not their nice syntax but how they help us wrangle this. Arrow functions share the surrounding scope with the parent context. This means that you don't need to create a reference to this when using an arrow function inside an object.

Let's say for example we had a cat and this cat needs to talk. In ES5 we would do the following:

In ES6 we can do the following instead:

Don't forget arrows have different scope

There is one gotcha with arrow functions, in babel they will remap this to undefined when there is no this. There are two ways to encounter it; Firstly, if you try to use the window or global object as this:

const windowIsNotThis = () => {
  console.log(this === window) // => false
}
windowIsNotThis()

That will log false because this has been remapped to undefined.

The second gotcha you can run into is when you try to use fat arrows on an object:

This errors because fat arrows use the this from the outer scope. A talk method that worked would look like this:

But instead of this self-invoking nonsense we can simply use an object shorthand:

That is all there is to ES6 arrows!