0

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 vars 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.

GDGDJKJ
  • 209
  • 1
  • 7
  • because i is 3 when the loop finishes, thus code inside the for loop will be using 3, not the current value of i for that iteration of the loop, which is what most people expect. console.log(0) is not correct. it is console.log(i), and `i` is evaluated when the function is called – user120242 Jul 11 '20 at 14:52
  • "it is console.log(i)" huh? why doesn't `i` get evaluated inside the function also? @user120242 – GDGDJKJ Jul 11 '20 at 15:17
  • the function assigned to funcs[i] is not executed until it is called. `i` is not evaluated for its value until the function is called, by which time `i`'s value has been incremented to 3. `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. – user120242 Jul 11 '20 at 15:36
  • "*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. – Bergi Jul 11 '20 at 17:07

0 Answers0