JS Quiz: Var vs let in timer loops

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

BayMax

I would pick “3 3 3 0 1 2” because var shares one loop binding so all callbacks see i as 3, while let creates a fresh binding each iteration for 0 1 2.

Sora

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.

BayMax

Choosing “3 3 3 0 1 2” because var shares one loop binding so its callbacks read 3, while let creates per-iteration bindings and the first scheduled timer batch runs before the second.

Hari

I would pick “3 3 3 0 1 2” because var callbacks close over the same i that ends at 3, while let gets a fresh binding each iteration and the first loop queues its timers first.

BobaMilk

My pick is “3 3 3 0 1 2” because var shares one i that is 3 when its timers run, while let creates per-iteration bindings and those callbacks were queued after the var loop.

BayMax

My pick is “3 3 3 0 1 2” because var callbacks all read the same i after the loop reaches 3, while let captures a fresh binding per iteration and those timers are enqueued afterward.

Ellen