1

I'm trying to validate my JavaScript closure understating and i come to strange behavior which i can't understand.

Lets write the first loop:

var funcs = [];
for (var i = 0; i < 3; i++) {
  funcs[i] = function() { 
    console.log("My value: " + i); 
  };
}
for (var j = 0; j < 3; j++) {
  funcs[j](); 
}

this will output

My value: 3
My value: 3
My value: 3

which is what i expected. But now lets change the second loop a little bit:

var funcs = [];
for (var i = 0; i < 3; i++) {
  funcs[i] = function() {
    console.log("My value: " + i);
  };
}
for (var i = 0; i < 3; i++) { // i only changed the j var to i 
  funcs[i]();
}

the output will be:

My value: 0 
My value: 1 
My value: 2

Could someone explain me why i get different results in the second example?

Here is a example which i wrote in angularjs: http://plnkr.co/edit/CipIQe9x8QBX7AFg4xfI?p=preview

Marian Ban
  • 8,158
  • 1
  • 32
  • 45
  • Dup? http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example – elclanrs Oct 17 '14 at 07:16
  • @elclanrs i understand how to avoid this problem but i expected the same behavior in my second example. I just don't know why i get correct results if i change the second loop parameter from j to i? – Marian Ban Oct 17 '14 at 07:18
  • 1
    MajoB, because `i` is the same variable in both cases, it is the same reference. Thus when looping with `i`, you're assigning the global `i` to the index, which is what is referred to in the closure. – elclanrs Oct 17 '14 at 07:23
  • 1
    Because the clusures are still bound to the same `i`. it will obviously print the current value of `i`. – YK1 Oct 17 '14 at 07:26
  • @elclanrs, YK1, thanks guys i just overlooked this fact :) – Marian Ban Oct 17 '14 at 07:27

0 Answers0