Masterbook/Chapter 6• 2 min read
View Raw Code on GitHub

Explain call stack and execution context

Explain call stack and execution context

The call stack is a structure that tracks what function is currently running and which function to return to when it finishes. Each time a function is called, the runtime creates a new frame and pushes it onto the stack. When the function returns, its frame is popped. If the stack grows too deep through unbounded recursion, a stack overflow error occurs.

An execution context is the environment in which a piece of JavaScript runs. It includes the scope chain, the bindings for variables and functions, the value of this, and references to outer environments. There is a global execution context created when the script starts. Each function call creates a new function execution context. During function creation, JavaScript also records the lexical
environment that will be used later when the function runs; this makes closures
possible.

Creation and execution happen in two phases for each context. In the creation phase, the engine allocates memory for declarations and sets up the scope and this binding. In the execution phase, the code runs line by line, reading and writing variables and calling other functions. When a function calls another function, a new context is created and pushed onto the call stack above the current one.

Examples

function a() {
  console.log("in a");
  b();
  console.log("back to a");
}
function b() {
  console.log("in b");
}
a();
// Stack behavior: enter a, enter b, exit b, back to a, exit a
// two-phase model inside a function
function sum(x, y) {
  // creation phase sets up x, y, and the environment
  return x + y; // execution phase reads values and returns
}
console.log(sum(2, 3));
// overflow example (do not run in production)
function recur() {
  return recur();
}
// recur(); // RangeError: Maximum call stack size exceeded

Common misconceptions

  1. The call stack shows asynchronous callbacks waiting. Only running frames are on the stack. Asynchronous callbacks wait in queues until picked up.
  2. The value of this is the same in every function. It depends on how the function is called, not just where it is defined.
  3. Execution context and scope are the same thing. Scope is part of the execution context, which includes additional details like this and the outer environment.

Practice questions

  1. Describe what happens on the call stack when a function calls another function that then throws an error.
  2. Explain how execution context creation and execution phases relate to hoisting.
  3. Why does unbounded recursion cause a stack overflow, and how can you avoid it.