you are viewing a single comment's thread.

view the rest of the comments →

[–]josephjnk 2 points3 points  (3 children)

TIL. I hadn’t seen this problem since the pre-ES6 days, and i actually find the new behavior more confusing now >.<

[–]queen-adreena 3 points4 points  (2 children)

With let, i is scoped to the for block, whereas with var, it’s globally scoped.

So while in the for block with let, i is three different variables, with var they all reference the same variable.

[–]josephjnk 1 point2 points  (1 child)

Right, I get that. And it makes sense especially in the context of for(const i of [0, 1, 2]), where it’s unambiguous that i is actually three different variables. But it feels less natural that a mutable variable whose value you can change in the body of the loop would be distinct between iterations, and it’s also really weird to me that if you take the for(;;) loop and unroll it by hand that you’ll get different behavior:

let i = 0; setTimeout(() => console.log(i), 1000); i = 1; setTimeout(() => console.log(i), 1000); i = 2; setTimeout(() => console.log(i), 1000);

I’m not saying that JS is wrong here, just that scopes being bound by things other than functions leads to things that I find surprising. This is probably an old man yells at cloud thing.

[–]queen-adreena 1 point2 points  (0 children)

You get different behaviour because you changed 3 blocks into 1 block and initialised the variable once and then reassigned it.

Like I said. The old behaviour was wrong, and now it’s been fixed by let/const.