How does let fix the var loop closure bug in JavaScript?
let is block-scoped and creates a fresh binding per iteration. Each callback closes over its own copy of i. With var, all callbacks share one i, which is the final value by the time they run.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in var Leaking From Blocks and Loops in JavaScript
Because var is function-scoped, not block-scoped. It ignores block boundaries (except function bodies). So a var inside an if is hoisted to the enclosing function or global scope. let and const are block-scoped and do not leak.
Because var is function-scoped. The loop variable exists in the enclosing function or global scope, not in the loop block. After the loop, the variable is still accessible. let is block-scoped and stays in the loop.
With an IIFE (immediately invoked function expression) that created a new function scope per iteration, capturing the current value of i as a parameter. This was the pre-ES6 workaround.
Still have questions?
Browse all our FAQs or reach out to our support team
