Skip to the page

Scope, hoisting and closures · core

Execution context, the call stack and hoisting

Before running a scope, the engine creates an execution context and registers all its declarations: function declarations get their full body, var gets undefined, and let, const and class stay uninitialised (the temporal dead zone) until their line runs.

The notes

What you must know

  • Each function call pushes an execution context onto the call stack: its variables, its this value and a link to the outer scope. Returning pops it. Too much recursion gives RangeError: Maximum call stack size exceeded.
  • Two phases: creation (declarations are registered) and execution (code runs line by line). 'Hoisting' is the name for the creation phase; code is not physically moved.
  • Function declarations are fully hoisted, so you can call them before their line. var f = function () {} hoists only f (as undefined), so calling it early is TypeError: f is not a function.
  • let, const and class are hoisted but uninitialised. Reading them before the declaration runs is ReferenceError: Cannot access 'x' before initialization. Even typeof throws in the TDZ, while typeof on an undeclared name returns 'undefined'.
  • The TDZ is about time, not text position: a function that reads a let variable is fine if it is called after the declaration line has run.
  • Default parameters have their own scope and TDZ: function f(a = b, b = 1) {} throws when called as f().
  • A let in an inner block shadows the outer variable from the start of the block, so reading the name before the inner let throws instead of reading the outer value.

The red pen

Common traps: mistake → fix

  • Mistake: let and const are not hoisted

    Fix: they are hoisted (they shadow outer names from the block start) but stay uninitialised.

  • Mistake: Hoisting moves code to the top

    Fix: nothing moves; declarations are registered before execution.

  • Mistake: typeof never throws

    Fix: it throws for a variable in its TDZ.

  • Mistake: A function expression is hoisted like a declaration

    Fix: only its variable is hoisted.

Easy to hard

Questions interviewers ask, easy to hard

  1. What is hoisting?
  2. Are let and const hoisted? What is the temporal dead zone?
  3. Function declaration vs function expression: which can you call before its line?
  4. Show a case where the TDZ depends on when code runs, not where it is written.
  5. What is an execution context? What is on the call stack during recursion, and why does a stack overflow happen?

Practise

Practise with these questions

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