Reputation: 351
can someone explain to me why the first code always print 3 and the second code work well?
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
buttons[i].addEventListener('click', function() {
console.log('You clicked button #' + i);
});
}
vs
var buttons = document.getElementsByTagName('button');
for (var i = 0; i < buttons.length; i++) {
let j = i;
buttons[j].addEventListener('click', function() {
console.log('You clicked button #' + j);
});
}
Upvotes: 0
Views: 64
Reputation: 17710
When you add your event listener, you are creating a function that references the i
variable from the enclosing scope. That variable gets incremented in your loop, and when the function is executed, you get the value of the variable at the end of the loop.
By creating another variable inside the loop, you are making a copy of the value at the time the loop is executed.
Upvotes: 1