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.
Hoisting in Loops and Conditionals in JavaScript
Does var inside an if block leak to the outer scope?
The answer
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.
Use let instead of var (each iteration gets a fresh binding), or wrap the body in an IIFE that captures the current value of i as a parameter.
Still have questions?
Browse all our FAQs or reach out to our support team
Want to upskill yourself?
Your learning library
Small steps. Big possibilities.
Find your next course. Build something great.