2

Why this JavaScript alerts allways 4 in when for-loop is for 3?

// alert
function reOrderLayers(layerToaAlter) {
alert(layerToaAlter);
}

// prepare
var laCount;
for (laCount = 1; laCount <= 3; laCount++) {
    var la = document.getElementById("layerChanger"+laCount);
    la.addEventListener("click", function () { reOrderLayers(laCount) });
}
Szymon Toda
  • 4,454
  • 11
  • 43
  • 62

6 Answers6

3

When loop is finished means i is >3, to preserve particular number in function call use closures:

  la.addEventListener("click", (function(count) { return function () { reOrderLayers(count) } })(laCount)  );
abuduba
  • 4,986
  • 7
  • 26
  • 43
2

The for loop continues until laCount == 4 (the last time the loop is executed the value is 3 and then it is incremented to 4 so that the loop test fails). Therefore the value is 4 after the for loop.

Mathias Schwarz
  • 7,099
  • 23
  • 28
1

Because when you click on the element; for loop is already finished and current value of laCount would be 4;

you should create a context to save laCount for each layerChanger:

function reOrderLayers(layerToaAlter) {
   alert(layerToaAlter);
}
function context(la, laCount){

         la.addEventListener("click", function () { reOrderLayers(laCount) });
  }

// prepare
var laCount, la;
for (laCount = 1; laCount <= 3; laCount++) {
    la = document.getElementById("layerChanger"+laCount);
    context(la, laCount);
}
Anoop
  • 23,044
  • 10
  • 62
  • 76
1

You didn't call reOrderLayers immediately in the loop but constructed a function literal. The literal will have a closure and it refers to the laCount variable in the environment which will be 4 when the click event is eventually fired.

billc.cn
  • 7,187
  • 3
  • 39
  • 79
0

Because:

var c = 0;
for(c = 1; c <= 3; c++) {};
alert(c); // alerts 4.
Hamish
  • 22,860
  • 8
  • 53
  • 67
0

During the first 3 iterations the for loop goes into the body and conducts the code you have inside. Once you're on the 4th iteration, lacount get incremented and the condition fails, so that you don't go into the loop again.

If you needed lacount to be 3 for some reason, you could try setting the initial for loop condition to i < 3.

Chase
  • 29,019
  • 1
  • 49
  • 48