This is Why I Love Fat Arrow Functions in ES6

Jonathan Hawley-Peters
2 min readAug 10, 2016

--

Since the moment I learned about arrow functions in ES6 (Ecma Script 6), I’ve been in love. As one of my favorite JavaScript Youtubers Mattias Petter Johansson points out in his video on arrow functions, they’re sooo much shorter that regular JS functions. Literally half the number of keystrokes.

Arrow functions in JavaScript — What, Why and How — FunFunFunction #32

Now in the above video, Mattias Petter Johansson wisely chooses to skip over the unique binding of the eternally confusing and sometimes useless ‘this’ keyword in Javascript. This is what I will talk about here. Get ready to revisit your confusion around or revise your mastery of the ‘this’ keyword.

Instead of looking left of the call time dot (eg. Math.sqrt(2), this = Math inside sqrt), ‘this’ in an ES6 arrow function gets bound to the ‘this’ of the lexical scope where the function was defined. It breaks some things you would normally expect to work, like adding a function to an object’s prototype:

Note: see below for the rest of the Cat constructor

How can this benefit us then? Glad you asked. You know all that annoying bind, call, apply, and ‘var context = this’ nonsense you have to do when invoking setInterval or setTimeout in a context you want preserved? ES6 arrow functions have got your back :)

Note: the following example is written in pseudoclassical style:

With a normal JS function, you would have to find some way to preserve the this context, but an ES6 arrow function takes care of this quietly and without fuss. I hope this gives you one more reason to love arrow functions the same way it did for me :)

--

--

Jonathan Hawley-Peters

Software Engineer obsessed with living a good, simple life rooted in reading, writing, cooking, movement, and time with loved ones