DEV Community

Discussion on: The Annoying Closure

Collapse
 
paxfeline profile image
David Newberry

I don't think it's the arrow function per se that's making the difference in your example, but rather the additional scope introduced by the showIndexWhenHover function. The variable 'index' in the event handler function binds to the index argument of showIndexWhenHover, rather than the global index variable.

The same code works as expected if the arrow functions are replaced with regular old function statements.

var index = 2387237;

const showIndexWhenHover  = function (div, index)  {div.addEventListener(
  'mouseenter', 
   function () { console.log(`${index} :: ${div.className}`); }
);};

([...(document.getElementsByTagName('div'))]).map(showIndexWhenHover);