Why does let in a setTimeout loop log 0, 1, 2 in JavaScript?
Because let is block-scoped and creates a fresh binding per iteration. Each callback closes over its own copy of i, which holds the value for that iteration. So when they run, each sees its own value.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in The setTimeout Loop Closure Bug: var vs let
Because var is function-scoped. There is one i for the entire loop. All callbacks close over the same i. By the time they run (after the loop), i is 3. Closures close over the variable, not the value.
The variable. A closure holds a reference to the variable, not a snapshot of its value. If the variable changes before the callback runs, the callback sees the updated value. This is why var in a loop logs the final value.
By creating a new function scope per iteration and capturing the current value of i as a parameter (j). Each callback closes over its own j, which is a snapshot of i at that iteration. This was the pre-ES6 workaround.
Still have questions?
Browse all our FAQs or reach out to our support team
