JavaScriptInterview preparation
Intermediate·Output prediction·2 min read

Why does a var loop print 3 three times?

Practice this question

Trace the code before revealing the explanation. Describe the output and the reason for its order.

Definition:

The var loop creates one shared function-scoped binding for i. Every callback closes over that same binding, and the loop has already set it to 3 before the timer callbacks run. Using let in the loop header creates a separate binding for each iteration.

Example and explanation:

JavaScript
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}
  • All callbacks share the same i; its value is 3 when they run.

  • Use let to create a separate binding per iteration: output becomes 0 1 2.

  • This is a closure-and-scope issue, not a timer choosing random values.

  • You can also capture each value through a separate function parameter, but let is clearer for this case.

Interview point:

  • Closures remember bindings, which is why all callbacks can observe the final value of one shared variable.
Adapted from 01_JAVASCRIPT_TYPESCRIPT.md · “Why does a var loop print 3 three times?”. Code examples are study fragments. Difficulty and core labels are editorial estimates; version-specific behavior should be checked against your project.