What is the difference between let and var in JavaScript?

← JavaScript answers

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: var ignores blocks such as if and for, while let and const stay inside them.
  • Hoisting: a var is available from the top of its function with the value undefined; a let exists but is unusable until its line runs (the temporal dead zone).
  • Redeclaration: var allows declaring the same name twice in one scope, let reports 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, 2

The 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.

Related questions

Start debugging smarter today

Try Bugsee for free — no commitments, no hidden fees.

Free sign upLive demoNo credit card required