← Back to JavaScript, page 5

javascript-0094 · Hard senior

What happens inside the engine when a function is called: execution contexts, the lexical environment, the scope chain, and the call stack?

Each function call creates an execution context pushed on the call stack. It holds a lexical environment with the function's variables and a link to the outer environment, which is fixed where the function was written. Name lookup walks this scope chain outward, which explains closures, shadowing, and hoisting. When a call returns, its context is popped, but its environment survives if a closure still references it.

Full answer

When code starts, the engine creates a global execution context. Each function call creates a new execution context and pushes it on the call stack, and returning pops it. The context at the top is the one that is running. Errors and stack traces are simply a printout of this stack.

An execution context holds the pieces needed to run a piece of code. The most important is the lexical environment, a record of the variables declared in the current scope plus a reference to the outer lexical environment. That outer link is decided when the function is defined, not when it is called, which is why JavaScript scoping is called lexical (or static). Before running the body, the engine creates the bindings in two phases: declarations are registered (var as undefined, functions with their bodies, let and const uninitialized until their line), and then code runs line by line. This is what hoisting and the temporal dead zone describe. Each block with let or const gets its own environment, which is why a let in a loop body is new every iteration.

When code reads a name, the engine looks in the current environment, then the outer one, and so on up to the global environment. This is the scope chain. The first match wins, which is shadowing, and a miss at the end is a ReferenceError. The value of this is part of the context and is decided by how the function was called, except for arrow functions, which take it from the outer environment.

Closures follow naturally. The environment of a finished call is not destroyed while a function that references it is still reachable. Only the call stack frame is popped; the environment object lives on the heap until the garbage collector finds it unreachable.

The stack has a limited size, so infinite or very deep recursion ends in a RangeError. Asynchronous callbacks start on an empty stack, which is why a stack trace inside a timer callback does not include the function that scheduled it.

javascript
const trace = () =>
  new Error().stack
    .split('\n')
    .slice(1)
    .map((line) => line.trim().match(/^at (?:async )?([\w$.<>]+)/)?.[1])
    .filter((name) => name && !['Object.<anonymous>', 'Module._compile'].includes(name) && !name.startsWith('Module.') && !name.startsWith('node:'))
    .slice(0, 4);

function outerCall() {
  return middleCall();
}
function middleCall() {
  return innerCall();
}
function innerCall() {
  return trace();
}
console.log('call stack, innermost first:', outerCall());

const level = 'global';
function outer() {
  const level = 'outer';
  function inner() {
    return level; // found in outer's environment, not in the caller's
  }
  return inner;
}
function caller() {
  const level = 'caller';
  return outer()(); // the caller's variable is never consulted
}
console.log('lexical lookup:', caller());

function makeCounter() {
  let count = 0; // lives on after makeCounter returns because inner functions reference it
  return {
    next: () => ++count,
    peek: () => count,
  };
}
const a = makeCounter();
const b = makeCounter();
a.next();
a.next();
b.next();
console.log('separate environments:', a.peek(), b.peek());

function hoistingDemo() {
  const before = typeof later;
  var later = 1;
  let result;
  try {
    result = tdz;
  } catch (error) {
    result = error.name;
  }
  let tdz = 2;
  return [before, result];
}
console.log('creation phase effects:', hoistingDemo());

const functions = [];
for (let i = 0; i < 3; i++) functions.push(() => i);
console.log('block environment per iteration:', functions.map((fn) => fn()));

function depth() {
  let n = 0;
  (function recurse() {
    n++;
    recurse();
  })();
}
try {
  depth();
} catch (error) {
  console.log('stack is finite:', error.name);
}

function scheduleIt() {
  setTimeout(function fromTimer() {
    console.log('timer trace includes the function that scheduled it:', trace().join(' ').includes('scheduleIt'));
  }, 0);
}
scheduleIt();

Run with Node.js v24.22.1 as js-94.js; two runs gave identical output. Output: call stack, innermost first: [ 'trace', 'innerCall', 'middleCall', 'outerCall' ] lexical lookup: outer separate environments: 2 1 creation phase effects: [ 'undefined', 'ReferenceError' ] block environment per iteration: [ 0, 1, 2 ] stack is finite: RangeError timer trace includes the function that scheduled it: false

Key points

  • Each call creates an execution context pushed on the call stack and popped on return.
  • A lexical environment holds the scope's variables and a link to the outer environment, fixed at definition.
  • Name lookup walks the scope chain outward; the first match wins.
  • Creation phase registers declarations; the execution phase runs code, which explains hoisting and the TDZ.
  • A returned function keeps its environment alive on the heap, which is a closure.

Common mistakes

  • Saying that scope depends on where a function is called, not where it is defined.
  • Believing the variables of a finished function are always freed; closures keep them.
  • Mixing up the call stack, which is runtime state, with the scope chain, which comes from the code structure.
  • Describing hoisting as moving code, not as registering names in the creation phase.

Follow-ups

  • How does the scope chain differ for a function created with new Function?
  • What changes about the scope and this for an arrow function?
  • How do async functions affect the call stack, and why do async stack traces differ?

Tips

  • Separate two ideas: the call stack (who called whom) and the scope chain (who contains whom).
  • Say "lexical" means decided where the code is written; use the caller versus outer example.
  • Tie closures, hoisting, and the TDZ back to the environment record.