Skip to the page

Scope, hoisting and closures · core

var, let and const

var is function-scoped and can be redeclared; let and const are block-scoped and have a temporal dead zone; const stops reassignment of the binding, not changes to the object it points to.

The notes

What you must know

  • Scope: var belongs to the nearest function (or the global scope); let and const belong to the nearest block { }.
  • Redeclaring: var a; var a; is allowed. let or const with the same name in the same scope is a SyntaxError.
  • const must be initialised and can't be reassigned. An object or array held in a const can still be changed (push works). Object.freeze makes it shallowly read-only.
  • In for (let i = ...), each iteration gets a new binding of i (the value is copied into the next iteration's binding), so callbacks created in the loop see different values. With var there is one shared i.
  • Top-level var in a classic script becomes window.x. Top-level let and const live in a separate scope and are not on window.
  • Use const by default, let when you must reassign, and avoid var.

The red pen

Common traps: mistake → fix

  • Mistake: const makes the value immutable

    Fix: only the binding is fixed; the object can still be mutated unless frozen.

  • Mistake: let in a for loop is just block scope

    Fix: it also creates a fresh binding per iteration, copying the previous value.

  • Mistake: let and const are not hoisted

    Fix: they are hoisted but not initialised (temporal dead zone).

Easy to hard

Questions interviewers ask, easy to hard

  1. What are the differences between var, let and const?
  2. Why can I push into a const array but not reassign it?
  3. Predict the setTimeout-in-a-var-loop output. Fix it three ways.
  4. What does top-level var do to window, and what do let and const do?
  5. Exactly how does let create a new binding per loop iteration? Predict a loop that changes i inside the body.

Your first interview is free

Sign up and start with a 15-minute interview with the full report, and an English conversation. No card needed.

Start your free interview