TIL that the arrow function introduced in ES6/2015 is NOT just short-hand for a normal function declaration. It uses lexical this scoping rather than the dynamic. Kyle Simpson argues in his excellent series You Don’t Know JavaScript that this was created in part because people misunderstand how this works and how to utilize bind.

Take the following example:

The above function’s setTimeout call-site is the global scope. This means this will not refer to the troll but to the global object, which in a browser, is the window, and dietaryRestriction does not exist globally.

Prior to arrow functions, we’d solve this by binding the context to the function, in other words, we’d pass in what this should refer to.

With arrow functions, we can rewrite the eat function as

Now this will always point to troll and this.dietaryRestriction will always be troll’s when the function executes after 3 seconds in the global scope.

Whether the convenience outweighs the potential confusion is up for debate, but understanding the difference is key to knowing how and when to use it.

Until next time!