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?