by pcthrowaway · 1y ago · 0 comments
In the first example:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i));
}
// prints "0 1 2" — as expected
let i = 0;
for (i = 0; i < 3; i++) {
setTimeout(() => console.log(i));
}
// prints "3 3 3" — what?
i's scope is outside the for loop in the second example, and the setTimeouts execute in the call stack (e.g. the next run of the event loop), after i has finished incrementing in the first event loop iterationConsider that you'd have the same issue with the older `var` keyword which is lexically scoped
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i));
}
// prints "3 3 3" because i is not block-scoped
If for some reason you really need some work run in the next call stack, and you need to use the value of a variable which is scoped outside the loop and modified inside the loop, you can also define a function (or use an iife) to pass the value of i in the current iteration into (rather than getting the reference of i in the event loop's next call stack) let i = 0;
for (i = 0; i < 3; i++) {
(
(x)=>setTimeout(()=>console.log(x))
)(i)
}
// prints 1 2 3Rust variable capture is implicit though, but it can't cause the problems described in the article, since mutable references are required to be unique.
I think it's fair to call that semantics "implicit".
The following code prints 1, 2, 3. It wouldn't do that if the variable was captured by value.
for (let i = 0; i < 3;) {
setTimeout(() => console.log(i));
i++;
} for (let i=0;i<3;i++) {
i+=10;
setTimeout(_=>console.log(i),30);
i-=10
}
Capture by value would print 10, 11, 12 that's the value when it was capturedCapture by reference would print 0,1,2
It's much easier to conceptualise it as
for (const i=0;i<3;i++) {
setTimeout(_=>console.log(i),30);
}
which is fine because i never changes. It is a different i each time.fancier example
for (let x = 0, y = 0; y < 2; x=x++<3?x:y++,0){
x+=10;
y+=10;
console.log("inline:",x,y);
setTimeout(_=>console.log("timeout",x,y),30);
x-=10;
y-=10;
}In short I'm not sure that they have misunderstood the scoping, they have probably understood it fine, they have remarked on the weirdness that different aspects of JavaScript enables.
Certainly with perfect understanding and knowledge of a language that you do not have to think about at all because it is so perfectly remembered nothing would ever be weird, it is the incidental behaviors of the language at time where you have to stop and think hey why is that, oh yeah, scoping rules and timeout in the call stack, damn!
What's the mistake that I made there? I just didn't explain why it happens. I briefly mentioned this in the later paragraphs — it makes sense to some people, but not to most.
> JS loops pretend their variables are captured by value
This has to do with how for loops work with iterators, but also what `let` means in variable declaration. You talk about 'unrolling a for loop' but what you're doing is 'attempting to express the same loop with while'. Unrolling would look like this;
// original:
for (let i = 0; i < 3; i ++) { setTimeout(()=>console.log(i)) }
// unrolled:
{ let i = 0; setTimeout(()=>console.log(i)) };
{ let i = 1; setTimeout(()=>console.log(i)) };
{ let i = 2; setTimeout(()=>console.log(i)) };
// original:
let i = 0;
for (i = 0; i < 3; i++) { setTimeout(()=>console.log(i)) };
// unrolled:
let i = 0;
{ i = 0; setTimeout(()=>console.log(i)); };
{ i = 1; setTimeout(()=>console.log(i)); };
{ i = 2; setTimeout(()=>console.log(i)); };
Now you can begin to explain what's going wrong in the second example; 'i' is declared with 'let' outside of the block, and this means the callback passed to the setTimeout is placed in the next stack frame, but references i from the outer scope, which is modified by the time the next stack frame is running.In the original example, a different 'i' is declared inside each block and the callback passed to setTimeout references the 'i' from its scope, which isn't modified in adjacent blocks. It's confusing that you're making this about how loops work when understanding what the loop is doing is only one part of it; understanding scoping and the event loop are 2 other important pieces here.
And then if you're going to compare a while loop to a for loop, I think a critical piece is that 'while' loops (as well as 'do .. while') take only expressions in their condition, and loop until the expression is false.
'for' loops take three-part statements, the first part of which is an initialization assignment (for which 'var' and 'let' work differently), and the second of which is an expression used as the condition. So you can declare a variable with 'let' in the initialization and modify it in the 'afterthought' (the third part of the statement), but it will be treated as if each iteration of the loop is declaring it within the block created for that iteration.
So yes, there are some 'for' loop semantics that are specific to 'for' loops, but rather than explain that, you appear to be trying to make a point about loops in general that I'm not following.
I'm not saying the examples won't help people avoid pitfalls with for and while loops, but I do think they'll be unable to generalize any lessons they take away to other situations in JS, since you're not actually explaining the principles of JS at play.
> Yes, the title makes no sense, but you'll see what I mean in just a second.
And yes, I didn't explain the exact mechanics of the ES spec which make it happen — but I would argue that "variables can be modified until they're out-of-scope" is even more unintuitive than just remembering this edge case. And I'm not trying to be an ECMAScript lawyer with the post, rather I'd just show a bunch of "probably unexpected" behaviors of JavaScript.
> lexical scope is "the portion of source code in which a binding of a name with an entity applies".
...both `let` and `var` are lexically scoped, the scopes are just different.
[0] https://tc39.es/ecma262/#sec-let-and-const-declarations [1] https://tc39.es/ecma262/#sec-variable-statement