Variables: var, let, const

Difficulty: Beginner

Question

What are the differences between var, let, and const in JavaScript, and when should you use each one?

Answer

var is function-scoped, can be redeclared, and is hoisted with the value undefined. let and const (ES2015) are block-scoped and sit in the Temporal Dead Zone until their declaration runs; let can be reassigned while const cannot. The modern rule is simple: use const by default, let when the binding must change, and avoid var.

Scope: function vs block

A block is anything between { }: an if, a for, a try, or a bare block. let and const live only inside the block where they are declared. var ignores blocks and attaches to the nearest enclosing function, or to the global scope if there is none.

Redeclaration, reassignment and hoisting

Featurevarletconst
ScopeFunctionBlockBlock
Redeclare in same scopeAllowedSyntaxErrorSyntaxError
ReassignAllowedAllowedTypeError
Must initialiseNoNoYes
Access before declarationundefinedReferenceError (TDZ)ReferenceError (TDZ)
Creates window property at top levelYesNoNo

All three are hoisted in the sense that the engine knows about them before the code runs. The difference is initialisation: var starts as undefined, while let and const stay uninitialised until the declaration line executes. Touching them earlier throws ReferenceError: Cannot access 'x' before initialization. That window is the Temporal Dead Zone.

const means a constant binding, not a frozen value

const stops you from pointing the name at something else. It does not make the value immutable. If the value is an object or array, you can still change its contents:

The loop closure trap

The most common interview demo: closures created inside a for (var i ...) loop all see the same i, so they all print the final value. With for (let i ...) the spec creates a fresh binding for every iteration, so each closure captures its own value. This is why setTimeout inside a loop printed 3, 3, 3 in old code and 0, 1, 2 in modern code.

What to use in real code

var vs let inside a loop. One shared i or one i per iteration. Switch the keyword under Tweak and replay.
  1. var is function-scoped: var i is hoisted once to the enclosing scope, so every iteration writes the same variable.
  2. let is block-scoped: for (let i ...) creates a fresh binding of i for each iteration.
  3. Closures capture variables: Arrows pushed in the loop keep a reference to whichever i they were created next to.
  4. Result: With var every arrow returns the final value (3, 3, 3); with let they return 0, 1, 2.

Code examples

Function scope vs block scope

function scopeDemo() {
  if (true) {
    var a = 'var leaks out of the block';
    let b = 'let stays inside';
    const c = 'const stays inside';
  }
  console.log(a);
  console.log(typeof b); // typeof on an undeclared name is safe
  console.log(typeof c);
}
scopeDemo();

var attaches to the function, so it is visible after the if block. let and const are confined to the block where they were declared.

Reassignment, redeclaration and const objects

var x = 1;
var x = 2;          // allowed, silently overwrites
let y = 1;
y = 2;              // allowed
// let y = 3;       // SyntaxError: Identifier 'y' has already been declared

const order = { id: 'ORD-101', amountPaise: 49900 };
order.amountPaise = 39900;   // allowed: mutating the object
// order = {};               // TypeError: Assignment to constant variable.

const frozen = Object.freeze({ status: 'PAID' });
frozen.status = 'REFUNDED';  // ignored (throws in strict mode)
console.log(x, y, order.amountPaise, frozen.status);

const protects the binding, not the object. Object.freeze makes the top-level properties read-only, but nested objects stay mutable.

Closures in loops

for (var i = 0; i < 3; i++) {
  setTimeout(() => console.log('var:', i), 0);
}
for (let j = 0; j < 3; j++) {
  setTimeout(() => console.log('let:', j), 0);
}

There is a single var i shared by all callbacks, and it is 3 by the time they run. let creates a new j per iteration, so each callback captures its own value.

Key points

Common follow-up questions

Interview tips

Concepts covered

var, let, const, Block Scope, Function Scope, Temporal Dead Zone

More JavaScript Interview questions