Your product could be here, in front of thousands of JavaScript developers. Sponsor this spot →
JavaScript Quiz

Why does let in a for loop fix the setTimeout closure problem?

Do you know what will be the output of this code?

JavaScript
for (let i = 0; i < 3; i++) {
  setTimeout(() => console.log(i));
}
Show answer and explanation

The answer is 0 1 2.

With let, each iteration gets a fresh copy of i. Every callback closes over its own binding, so they print the values from their own iteration.

Take the full quiz Next question →

More Closures questions

  1. How does a closure counter work in JavaScript?
  2. Why does var in a loop with setTimeout print 3 3 3?
  3. Do two closures from the same function share state?
  4. Does a JavaScript closure capture the value or the variable?
  5. How do closures create private variables in JavaScript?

Related topics