Why does var leak out of for loops in JavaScript?
Because var is function-scoped, not block-scoped. The loop variable exists in the enclosing function (or global scope). Using let makes the variable block-scoped and confined to the loop.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Hoisting Pitfalls and Bugs to Avoid in JavaScript
Using a var before assignment (returns undefined or NaN), var leaking out of loops, calling a function expression before assignment (TypeError), accidental shadowing, and TDZ surprises with let and const.
Use const by default and let when you must reassign, avoid var, declare variables at the top of their scope, use const for function expressions, and enable strict mode to catch silent issues.
Because the var variable is hoisted with undefined. The variable exists, so no ReferenceError, but undefined() throws TypeError: x is not a function. Use const and declare before calling.
Still have questions?
Browse all our FAQs or reach out to our support team
