Are function declarations inside blocks hoisted differently than var?
In ES6+, function declarations in blocks are hoisted to the block scope, not the function scope. Behavior varied in older engines, so prefer function expressions with const for predictable behavior.
Verify This Answer
Cross-check this information using these trusted sources:
More FAQs in Hoisting in Loops and Conditionals in JavaScript
Because var is function-scoped. There is one i shared by all iterations. By the time the setTimeout callbacks run, the loop has finished and i equals the final value, so all callbacks log that value.
Because let is block-scoped and the spec gives each iteration a fresh binding. Each closure captures its own copy of i, so callbacks log 0, 1, 2 instead of the final value.
Yes. var 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.
Still have questions?
Browse all our FAQs or reach out to our support team
