Tech Interview RoomStudy guides

JavaScript

What is the difference between var, let and const?

Beginner · 2 min read · Lesson 1 of 12 in JavaScript

All three declare variables, but they differ in scope, hoisting and reassignment.

Scope

  • var is function-scoped: a var inside an if or for block is visible in the whole enclosing function.
  • let and const are 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).
  • var is initialised to undefined, so reading it early gives undefined.
  • let and const stay uninitialised until their line runs. Reading them earlier throws a ReferenceError. The gap between the start of the block and the declaration is the temporal dead zone (TDZ).

Reassignment

  • var and let can be reassigned.
  • const cannot be reassigned, but the value is not frozen: const user = {} still allows user.name = 'A'. Use Object.freeze for 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.