DEV Community

Taufik Nurrohman
Taufik Nurrohman

Posted on

When Does Arrow Function Become Useless?

Arrow function loses its benefits when used like this:

for (let i = 0, j = elements.length; i < j; ++i) {
  elements[i].addEventListener('click', () => {
    // `this` of what?
    alert(this.textContent);
  }, false);
}
Enter fullscreen mode Exit fullscreen mode

And like this:

for (let i = 0, j = elements.length; i < j; ++i) {
  elements[i].addEventListener('click', () => {
    // The value of `i` has already changed to the maximum index
    // because the loop is already complete even before
    // we decide to click on `elements[i]`
    alert(elements[i].textContent);
  }, false);
}
Enter fullscreen mode Exit fullscreen mode

Any others?

Latest comments (1)

Collapse
 
miketalbot profile image
Mike Talbot ⭐ • Edited

Agree on the first one, an arrow function isn't called with the this from the event listener. A normal function would be.

In the second:

Any kind of local function, not just an anonymous function will have a problem if you use a closure over a value from the outside - e.g. your loop iterator in the second example.

Either use a forEach loop that will capture the closure variable you need or do let element = elements[i], then use element in the closure. This technique often leads to faults due to loop iterators (I know WebStorm tells me if I try to write it) but is super useful in other circumstances.

Arrow functions are useless anywhere you'd do a bind not to the current execution context or in any other place that a this might be useful.

myClass.prototype.doIt = ()=>console.log(this) // not going to fly
Enter fullscreen mode Exit fullscreen mode