Nave Hazan
Nave Hazan

Reputation: 351

why in the example the "for loop" work well with "let", and not work with "var"?

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

here is my codepen

Upvotes: 0

Views: 64

Answers (1)

jcaron
jcaron

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

Related Questions