OutputNot attempted
var vs let in a loop with timers
for (var i = 0; i < 3; i++) { setTimeout(() => console.log('var', i));}for (let j = 0; j < 3; j++) { setTimeout(() => console.log('let', j));}Spaces and quote style don’t matter · write a thrown error as TypeError
Show answer & explanation
The expected output comes from actually running the snippet; opening this shows it next to the explanation.
var has ONE binding for the whole loop; by the time timers fire it is 3. let creates a fresh binding per iteration. Fix var without let: IIFE (function (t) {...})(i), or setTimeout(console.log, 0, "var", i), or .bind(null, i).
Deep dive (read after you answer)
A closure is a function plus the variables it could see where it was created. It keeps a live reference to those bindings, not a copy of their values, so what it logs depends on how many bindings exist and what they hold when it finally runs.
setTimeout callbacks run later, after the loop has finished and the call stack is empty. So the real question is: how many i bindings did the loop create?
varis function-scoped. The loop has a singleithat every callback shares, and the loop leaves it at the value that failed the condition.letin aforheader is special: the spec creates a new binding per iteration and copies the current value into it, so each callback closes over its ownj.
Common mistakes:
- Thinking the timer delay matters. Even
setTimeout(fn, 0)waits for the loop to end. - Thinking a closure "captures the value". It captures the variable; that is why later writes are visible.
- Fixing it with
constin a classicforloop:i++would then throw.
Without let, give each callback its own binding: wrap the body in an IIFE that takes i as a parameter, use .bind(null, i), or pass i as an extra setTimeout argument. In an interview, say "one binding vs one per iteration" and you have explained the whole puzzle.