Javascript multiple dynamic addEventListener created in for loop – passing parameters not working

Problem is closures, since JS doesn’t have block scope (only function scope) i is not what you think because the event function creates another scope so by the time you use i it’s already the latest value from the for loop. You need to keep the value of i.

Using an IIFE:

for (var i=0; i<names.length; i++) {
  (function(i) {
    // use i here
  }(i));
}

Using forEach:

names.forEach(function( v,i ) {
  // i can be used anywhere in this scope
});

Leave a Comment