1. Home
  2. Interview Questions
  3. JavaScript
  4. Why does a for loop with var and setTimeout print the same v…

Try answering first

In a real interview nobody shows you the answer. Think it through (or type it), then reveal the answers and rate yourself.

1 Answer

0 0
InterviewQuestions Team ✔ Expert answer ✔ Best answer ·

Short answer: var is function-scoped, so the loop has only one variable i. All the setTimeout callbacks close over that same variable and run after the loop has finished, so they all see its final value. Using let creates a fresh binding of i for each iteration, so each callback sees its own value.

Detailed explanation

This question tests three things together: scope, closures and the event loop.

  • Scope: A var declared in a for header is not scoped to the loop. It belongs to the enclosing function, or to the global scope. There is exactly one i, and every iteration updates it.
  • Closures: Each arrow function passed to setTimeout captures a reference to the variable i, not a copy of its value at that moment.
  • Event loop: setTimeout only schedules the callback. Even with a delay of 0, the callback waits until the current synchronous code, including the whole loop, has finished. By then i has been incremented to the value that made the loop condition false.

With let, the language specification treats for loops specially. For every iteration, the engine creates a new lexical environment with its own copy of i. It initialises that copy from the previous iteration's value and then runs the increment. Each callback therefore closes over a different binding, and each binding keeps the value it had in that iteration.

Before ES6, developers solved this with an IIFE (immediately invoked function expression). The IIFE creates a new function scope per iteration and passes the current value in as a parameter. Another older fix is the extra-arguments form of setTimeout, which passes the current value to the callback when it is scheduled.

Example

// Problem: prints 3, 3, 3
for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log(i), 0);
}

// Fix 1: let gives a new binding per iteration -> 0, 1, 2
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log(j), 0);
}

// Fix 2 (pre-ES6): IIFE captures the current value -> 0, 1, 2
for (var k = 0; k < 3; k++) {
  (function (n) {
    setTimeout(function () { console.log(n); }, 0);
  })(k);
}

// Fix 3: setTimeout passes extra args to the callback -> 0, 1, 2
for (var m = 0; m < 3; m++) {
  setTimeout(function (n) { console.log(n); }, 0, m);
}

console.log(i); // 3 -- var leaked outside the loop
// console.log(j); // ReferenceError: j is not defined

The same bug appears in real code when you attach click handlers inside a var loop. Every button ends up reporting the last index. Switching to let, or using forEach, fixes it, because forEach calls a new function for each element.

Common mistakes

  • Saying setTimeout(fn, 0) runs the callback immediately. It runs only after the call stack is empty, which is after the loop has finished.
  • Expecting the output to be 2 instead of 3. The loop stops only after i becomes 3 and the condition i < 3 fails.
  • Using const in a classic for (const i = 0; i < 3; i++) loop. The first iteration runs, then i++ throws a TypeError, because a const cannot be reassigned. const is fine in for...of and for...in, which create a new binding each iteration.
  • Explaining the fix as "let copies the value into the closure". The correct explanation is that let creates a new binding per iteration, and each closure references its own binding.

Follow-up questions

  • If you modify j inside the body of a let loop, does the next iteration see the change?
  • Why does const work in for (const item of list) but not in a classic counter loop?
  • What happens to var declared at the top level of a browser script compared with let?

Interview tip: State the output first, then walk through scope, closure and event loop in that order. Interviewers want to see that you understand why the bug happens, not just that let fixes it.

Reviewed by the Interview Questions editorial team · Last updated

How well did you know this?

Rate yourself to track progress, build your streak and get “didn't know” questions in your revision list.

Your Answer

More medium JavaScript questions

All medium questions →

Related Questions

‹
Q3 of 10 · JavaScript
Next ›

Interview Questions

Free interview questions and answers, MCQ practice, online tests, mock interviews and group discussions — everything you need to crack your next interview.
📍 Dasardot LLC
1309 Coffeen Avenue STE 1200
Sheridan, Wyoming 82801
USA