The Call Stack

How JavaScript tracks where it is in your code. One thing at a time.

How It Works

A stack of function calls. Last in, first out (LIFO).

// The call stack tracks function execution:
// • Function called → PUSH frame onto stack
// • Function returns → POP frame off stack
// • Stack empty → program is idle

function third() { return "done"; }
function second() { return third(); }
function first() { return second(); }
first();

Call Stack visualization:

third()
second()
first()
global()

← top of stack (currently executing)

Step by Step

Watch functions push and pop from the stack.

global()

Program starts

first();

1 / 7

Stack Overflow

When the stack gets too deep, it crashes.

// Infinite recursion → stack overflow:
function forever() {
  forever(); // calls itself with no end condition
}
forever();
// RangeError: Maximum call stack size exceeded

// The stack fills up until the engine stops it:
// forever() → forever() → forever() → forever() → ...
// Stack size varies: ~10,000-25,000 frames (depends on engine)

⚠️ Stack overflow means your recursion has no base case, or it's too deep. Always ensure recursive functions have an exit condition that will be reached.

Recursion

Functions that call themselves with a base case.

function factorial(n) {
  if (n <= 1) return 1; // base case!
  return n * factorial(n - 1);
}
factorial(4); // 24

Each call adds a frame to the stack. The base case (n <= 1) stops the recursion.

💡 Always needs a base case to prevent stack overflow
1 / 3

Single-Threaded

JavaScript has one call stack. One thing at a time.

// JS is single-threaded:
// Only ONE function executes at a time.
// If a function is slow, everything else waits.

function slowTask() {
  // Blocks the thread for 3 seconds
  const end = Date.now() + 3000;
  while (Date.now() < end) {} // busy wait
  console.log("Done!");
}

slowTask(); // UI freezes during this!
console.log("After"); // waits 3 seconds

How async solves this:

When you use setTimeout, fetch, or addEventListener, the task is handed off to the browser/runtime. The call stack stays free. When the task completes, a callback is queued and executed when the stack is empty — this is the Event Loop.

FAQ

Common questions about the call stack.