#5: var in a setTimeout loop
Topic: closures · Difficulty: ★★
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i));
}Output
3 3 3
Why
var is function-scoped, not block-scoped, so all three arrow functions close over the SAME variable i — not a copy per iteration. The loop finishes synchronously first, leaving i at 3 (the value that failed i < 3). Only then does the event loop run the queued timeouts, and each one reads the current value of that single shared i: 3, three times. Declaring the loop variable with let creates a fresh binding per iteration and would print 0, 1, 2.