2

I've seen examples of closure and I thought I understand them, until I decided to do this:

var f = [];
for (var i = 0; i < 2; i++) {
    f[i] = function foo(a) {
        var h = i;
        function bar() {
            console.log(h);
        }
        if (a == 1)
            bar();
    }
}

for (var j = 0; j < 2; j++) {
    console.log(f[j](1));
}

The output is this:

2
2

When I thought it would be 0, 1 since I created an outer function foo where I store i in the variable h Can someone explain what happens here and why those setTimeout examples work correct?

j08691
  • 204,283
  • 31
  • 260
  • 272
  • You have no `setTimeout` calls? [This question](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) is highly related, possibly a duplicate. – James Thorpe Oct 30 '15 at 16:43
  • 5
    You're only assigning `i` to `h` when the function is actually called. At that time `i` is already 2. – Yoshi Oct 30 '15 at 16:46
  • @Yoshi Ok now I got it. Was easy actually. Thank you! – Anton Poliakov Oct 30 '15 at 17:06

1 Answers1

2

For the desired output update your code to following

var f = [];
for (var i = 0; i < 2; i++) {
  f[i] = (function(i){ 
              return function foo(a) {
                 var h = i;
                 function bar() {
                     console.log(h);
                 }
                 if (a == 1)
                    bar();
             }
         })(i);
}

for (var j = 0; j < 2; j++) {
    console.log(f[j](1));
}
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59