I know that I should use let
and const
, but I still want to understand this.
Look at this code:
var funcs = [];
for (var i = 0; i < 3; i++) {
funcs[i] = function() {
console.log(i);
};
}
for (var j = 0; j < 3; j++) {
funcs[j]();
}
I understand that var
s are hoisted, and that that is happening in this case because blocks are not scopes. This in mind, I can guess that javascript is reading that code as follows:
var i;
...
for(i = 0; i < 3; i++){
...
}
...
But I don't see how that should be a problem. The way this is translating in my mind is as such:
{// i = 0;
funcs[0] = function() {
console.log(0);
};
}
...
The only way in which I think that this makes sense is if javascript is storing i
by reference, and not value. Could someone please elaborate on this?
Answer:
console.log(i=0)
is never true, it is evaluated as:funcs[i=0] = function() { console.log(i) }
. the function has been declared, but has not been called, and that i has not been evaluated.from user120242.
"this makes sense is if javascript is storing i by reference, and not value." - yes, closures in javascript do capture variables by reference, they do not capture the current value of a variable when the closure is created.
from Bergi.