loading...

When Does Arrow Function Become Useless?

taufik_nurrohman profile image Taufik Nurrohman ・1 min read

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);
}

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);
}

Any others?

Discussion

markdown guide
 

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