When (to and not to) use ES6 Arrow functions in JavaScript?

It is important to note that arrow functions are anonymous, which means that they are not named.

This anonymity creates some issues:

When you get an error, you will not be able to trace the name of the function or the exact line number where it occurred.

If your function needs to have a self-reference at any point (e.g. recursion, an event handler that needs to unbind), it will not work.

Main benefit: No binding of ‘this’

In classic function expressions, the this keyword is bound to different values based on the context in which it is called. With arrow functions, however, this is lexically bound. It means that it usesthis from the code that contains the arrow function.

In the ES5, .bind(this) is required to help pass the this context into the function. Otherwise, by default this would be undefined.

When you should not use Arrow Functions

When you call cat.jumps, the number of lives does not decrease. It is because this is not bound to anything, and will inherit the value of this from its parent scope.

If you need your context to be dynamic, arrow functions are not the right choice. Take a look at this event handler below:

If we click the button, we would get a TypeError. It is because this is not bound to the button but instead bound to its parent scope.

It is worth taking into consideration the variety of syntax we covered earlier. With regular functions, people know what to expect. With arrow functions, it may be hard to decipher what you are looking at straight away.

When you should use them

Arrow functions shine best with anything that requires this to be bound to the context, and not the function itself.

Despite the fact that they are anonymous, Using them with methods such as map and reduce, makes code more readable.

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Abhay Jain

Abhay Jain

Developer with 3 yrs of industrial experience in developing scalable web applications.