ES6 Fat Arrow Functions

September 17, 2015

Like it or not, ES6 and it’s many features are coming to a browser near you soon – if they’re not implemented already!

The good news we’ll cover today? You (basically) never have to type the word “function” again! Think of all the time you’ll save!

Fat Arrow Functions

Let’s dive into some examples, comparing the ES5 way of doing things to the ES6 way.

// Mapping over an array
var arr = [1, 2, 3, 4, 5];

// ES5
arr.map(function(number) { return number * 2 });

// ES6
arr.map(number => number * 2);

// Think of the savings!

Check out how we can do IIFE’s with ES6!

// ES5
(function () {
  console.log('Immediately-Invoked Function Expression');
})();

// ES6

() => {
  console.log('Immediately-Invoked Function Expression');
}();

// You're welcome, fingers!

Lexical this

One big difference to take note of is that unlike the functions you’re used to, fat arrow functions have a lexically bound this.

Let’s demonstrate this with an age old JavaScript problem.

// Say you have a global variables named foo
var foo = 'I am global';

// Then you have a function named Bar
function Bar() {

 // Bar has it's own variable named foo
 this.foo = 'I am local to bar';

 // Bar has a setTimeout inside of it
 setTimeout(function log() {
 // Current scope is bound to the window, so this will console log
 console.log(this.foo); // I am global
 }, 1000);
}

var baz = new Bar();

In the past, this giant pain had to be solved by binding Game’s `this` to the setInterval or doing something hacky like var self = this; outside the setInterval. Now with fat arrow functions it works like you’d thing it would.

// Say you have a global variables named foo
var foo = 'I am global';

// Then you have a function named Bar
function Bar() {

 // Bar has it's own variable named foo
 this.foo = 'I am local to bar';

 // Bar has a setTimeout inside of it
 setTimeout(() => {
 // Current scope is now set to Bar, so it console logs
 console.log(this.foo); // I am local to bar
 }, 1000);
}

var baz = new Bar();

While this is great for our particular use case, it’s important to remember whenever using fat arrow functions.