DEV Community

Discussion on: When Does Arrow Function Become Useless?

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