What is the difference between var, let and const?
All three declare variables, but they differ in scope, hoisting and reassignment.
Scope
varis function-scoped: avarinside aniforforblock is visible in the whole enclosing function.letandconstare block-scoped: they exist only inside the nearest{ }.
Hoisting and the temporal dead zone
- All three are hoisted (the engine knows about them before the line runs).
varis initialised toundefined, so reading it early givesundefined.letandconststay uninitialised until their line runs. Reading them earlier throws aReferenceError. The gap between the start of the block and the declaration is the temporal dead zone (TDZ).
Reassignment
varandletcan be reassigned.constcannot be reassigned, but the value is not frozen:const user = {}still allowsuser.name = 'A'. UseObject.freezefor shallow immutability.
What to use
Default to const, use let only when the variable must change, and avoid var in modern code.
Example
js
for (var i = 0; i < 3; i++) setTimeout(() => console.log('var', i)); // 3 3 3
for (let j = 0; j < 3; j++) setTimeout(() => console.log('let', j)); // 0 1 2
console.log(a); // undefined (var is hoisted and initialised)
var a = 1;
// console.log(b); // ReferenceError: b is in the TDZ
let b = 2;The let loop prints 0 1 2 because each iteration gets a new binding, so every callback closes over its own j. The var loop shares one i, which is 3 by the time the timers fire.
Follow-up questions interviewers ask
Try answering each one before you open it.
Does const make an array immutable?
No. const only stops the variable from pointing at a different array. arr.push(4) still works. For immutability use Object.freeze(arr) (shallow), spread copies when updating ([...arr, 4]), or a library such as Immer. In TypeScript, readonly number[] or as const catches mutation at compile time.