r/learnjavascript • u/ClickOk5811 • Oct 13 '26
Why var in a loop prints 3, 3, 3. Tracing it like a debugger watch window
The classic one, but I find it easier to understand when you look at the value of i at the moment each callback actually runs, not at the moment it’s created.
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// prints: 3 3 3Here’s what a watch window on i would show:
step i
----------------------------------------
loop starts 0
schedule callback #1 0 (callback stored, not run)
i++ 1
schedule callback #2 1 (stored, not run)
i++ 2
schedule callback #3 2 (stored, not run)
i++ 3
condition 3 < 3 is false 3 loop ends
--- timers fire now ---
callback #1 reads i 3
callback #2 reads i 3
callback #3 reads i 3The callbacks don’t capture the value i had when they were created. They capture the variable. And with var there is only one i for the whole function, so all three callbacks point at the same box. By the time the timers fire, the loop has long finished and the box holds 3.
With let:
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i), 0);
}
// prints: 0 1 2The loop creates a fresh binding of i for each iteration, so each callback closes over its own box. In the watch window you’d see three different i variables, each stuck at the value it had in its iteration.
Two things that make this easier to remember:
setTimeout(..., 0)doesn’t mean “now”. The callback still waits until the current code finishes, which is why the loop is already done.- the old fix was an IIFE (
(function(j){ ... })(i)) that copied the value into a new scope.letdoes the same thing for you.
If you ever see this behaviour in code you didn’t write, check for var first.
Does anyone have a favorite way of explaining this to someone who’s new to closures? The watch-window view is the one that clicked for me when I wrote it down, but I’m sure there are better ones.