var is scoped to the whole function and is hoisted as undefined; let is scoped to the nearest block and throws if you touch it before its declaration.
The practical differences come down to scope and timing.
- Scope:
varignores blocks such asifandfor, whileletandconststay inside them. - Hoisting: a
varis available from the top of its function with the valueundefined; aletexists but is unusable until its line runs (the temporal dead zone). - Redeclaration:
varallows declaring the same name twice in one scope,letreports a syntax error.
for (var i = 0; i < 3; i++) setTimeout(() => console.log(i)); // 3, 3, 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log(j)); // 0, 1, 2The loop example shows why let is the safer default: every iteration gets its own binding. Prefer const for values you never reassign and let for the rest.
