-2
for (var i = 0; i < 5; i++) {
  var btn = document.createElement('button');
  btn.appendChild(document.createTextNode('Button ' + i));
  btn.addEventListener('click', function(){ console.log(i); });
  document.body.appendChild(btn);
}

In the above code - the output will be 5 always no matter what button is pressed because I understand in js it is by referene, by the time the loop completed the final value will be updated in to 'i' - but 1 question I have is why 5 - I thought it is 4 - once the value of i is 4 shouldn't it come out of the loop?? Am I missing some understanding with 'for' loops?

1 Answers1

0

Your question is not about the closure, but rather about the loop, right? The closure is a different story, but the loop is straightforward - it does the increment step before checking to see if it passes the conditional:

The order is:

  • Initialize i to 0
  • _
  • Check to see if i < 5 (it is)
  • Execute the body
  • Increment i to 1
  • _
  • Check to see if i < 5 (it is)
  • Execute the body
  • Increment i to 2
  • _
  • Check to see if i < 5 (it is)
  • Execute the body
  • Increment i to 3
  • _
  • Check to see if i < 5 (it is)
  • Execute the body
  • Increment i to 4
  • _
  • Check to see if i < 5 (it is)
  • Execute the body
  • Increment i to 5
  • _
  • Check to see if i < 5 (it is not)
  • End the loop
Joe Enos
  • 39,478
  • 11
  • 80
  • 136
  • Thanks So much, it makes sense now, I was under an assumption that the loop will break as soon as it is 4 - missed incremented before part.. – user3645936 May 13 '16 at 19:29
  • @user3645936 The loop breaks when the condition in the second part of the `for()` header fails. How could it break as soon as it's 4 when the condition is `i < 5`? – Barmar May 13 '16 at 19:57