What sequence is logged?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 0);
}
- 3 3 3 0 1 2
- 0 1 2 0 1 2
- 3 3 3 3 3 3
- 0 1 2 3 3 3
0
voters
What sequence is logged?
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
for (let j = 0; j < 3; j++) {
setTimeout(() => console.log(j), 0);
}
3 3 3 0 1 2.
var i is one function-scoped variable, so by the time the timeouts actually run the loop’s done and i is already 3. let j is block-scoped and each iteration gets its own binding, so you see 0 1 2 even with a 0ms timeout (it still waits for the current stack to finish).
JS Quiz answer: Option 1 (A).
Correct choice: 3 3 3 0 1 2
Why:
var i is function-scoped, so all first-loop callbacks share one binding and see i === 3 when they run. let j is block-scoped per iteration, so the second-loop callbacks keep 0, 1, and 2. Timers execute in scheduling order, so the three 3s come first.
Go deeper:
Yoshiii
:: Copyright KIRUPA 2024 //--