Javascript Fundamentals · Interview Fundamentals

var, let, and const

hoisting and the temporal dead zone

var, let, and const

console.log(x); // undefined
var x = 1;

console.log(y); // ReferenceError: Cannot access 'y' before initialization
let y = 2;

const list = [];
list.push(1); // fine — the array is mutated, not reassigned

Both reads happen before the declaration, yet one quietly prints undefined and the other throws. All three keywords declare variables, but they differ in scope, reassignment, and when they become usable.

  • var is function-scoped (or global). It is hoisted to the top of its function and initialised to undefined, so reading it before its line gives undefined rather than an error.
  • let and const are block-scoped: they exist only inside the nearest { ... }. They are hoisted too, but not initialised — the gap between the start of the block and the declaration is the temporal dead zone, and touching the variable there throws a ReferenceError.
  • const must be given a value at declaration and cannot be reassigned. It is not immutable: the binding is fixed, but the object it points at can still be mutated.

Prefer const, fall back to let when you must reassign, and avoid var. A let binding inside a loop is also fresh on every iteration, which is why closures capture the right value where var would share one.

You are about to answer a short quiz on var, let, and const.

  1. `var` is block-scoped, so it does not exist outside the nearest `{ ... }`.
  2. Reading a `let` variable before its declaration throws a ___.
  3. A `var` read before its declaration line evaluates to `undefined` rather than throwing.
  4. The window between the start of a block and a `let` declaration is called the ___.
  5. A `const` binding can be reassigned as long as the new value has the same type.
  6. Mutating an object held in a `const` binding is allowed.
  7. Inside a loop, a closure created with ___ gets a fresh binding on each iteration.