- Home
- Interview Questions
- JavaScript
- 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
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
vardeclared in aforheader is not scoped to the loop. It belongs to the enclosing function, or to the global scope. There is exactly onei, and every iteration updates it. - Closures: Each arrow function passed to
setTimeoutcaptures a reference to the variablei, not a copy of its value at that moment. - Event loop:
setTimeoutonly schedules the callback. Even with a delay of 0, the callback waits until the current synchronous code, including the whole loop, has finished. By thenihas 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 definedThe 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
ibecomes 3 and the conditioni < 3fails. - Using
constin a classicfor (const i = 0; i < 3; i++)loop. The first iteration runs, theni++throws a TypeError, because a const cannot be reassigned.constis fine infor...ofandfor...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
jinside the body of aletloop, does the next iteration see the change? - Why does
constwork infor (const item of list)but not in a classic counter loop? - What happens to
vardeclared at the top level of a browser script compared withlet?
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
Related Questions
- Why can you call a function declaration before it is defined but not a function expression? · JavaScript · 1 ans
- Why can't try/catch catch an error thrown inside a setTimeout callback or a promise? · JavaScript · 1 ans
- How is a lambda different from an anonymous inner class in Java beyond shorter syntax? · Java · 1 ans
- What is the temporal dead zone, and are let and const actually hoisted? · JavaScript · 1 ans
- How do you write a Python decorator that accepts its own arguments? · Python · 1 ans
- Why do lambdas created inside a loop all return the last loop value in Python? · Python · 1 ans
- What are tagged template literals in JavaScript and when would you actually use one? · JavaScript · 1 ans
- How do try, catch and finally work, and what happens if finally contains a return? · JavaScript · 1 ans
🙋 Was this asked in your interview?
Which company? (optional — adds this question to the company's page)