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:
Harder to debug
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.
No self-referencing
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
Object methods
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.
var cat = {
lives: 9,
jumps: () => {
this.lives--;
}
}
Callback functions with dynamic context
If you need your context to be dynamic, arrow functions are not the right choice. Take a look at this event handler below:
var button = document.getElementById('press');
button.addEventListener('click', () => {
this.classList.toggle('on');
});
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.
When it makes your code less readable
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.