Difficulty: Beginner
What are the differences between var, let, and const in JavaScript, and when should you use each one?
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.
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.
var declared inside an if is visible after the if ends, which leads to accidental leaks and name collisions.var in a classic browser script becomes a property of window (window.count). Top-level let and const do not.| Feature | var | let | const |
|---|---|---|---|
| Scope | Function | Block | Block |
| Redeclare in same scope | Allowed | SyntaxError | SyntaxError |
| Reassign | Allowed | Allowed | TypeError |
| Must initialise | No | No | Yes |
| Access before declaration | undefined | ReferenceError (TDZ) | ReferenceError (TDZ) |
Creates window property at top level | Yes | No | No |
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 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:
const cart = []; cart.push(item) works.cart = [] throws TypeError: Assignment to constant variable.Object.freeze(cart), which is shallow, or keep data immutable by convention and create new objects with spread.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.
const for almost everything: imported modules, functions, config objects, values computed once. It signals intent to readers and lets linters catch accidental reassignment.let for counters, accumulators, and values reassigned in branches.var only when maintaining legacy code. ESLint's no-var and prefer-const rules enforce this in most codebases, including Airbnb and the default TypeScript configs teams use.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.
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.
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.
var, let, const, Block Scope, Function Scope, Temporal Dead Zone