Course contentsShow
← JavaScript
Lesson 1184 of 2,72327. The Event LoopFree lesson

Visualizing the Stack During Execution

As functions call other functions, frames pile up; when they return, frames are popped in reverse order.

Visualizing the Stack During Execution

You'll learn: How the call stack grows and shrinks as functions call each other and return.

When your JavaScript code runs, the call stack behaves like a stack of plates. Each time a function is called, a new "plate" (stack frame) is added to the top. When a function finishes, its plate is removed from the top. This LIFO (Last In, First Out) order means the most recent function must complete before control returns to earlier ones.

How Functions Pile Up

Imagine this scenario:

function first() {
  second();
  console.log("Back in first");
}

function second() {
  third();
  console.log("Back in second");
}

function third() {
  console.log("In third");
}

first();

The stack grows like this:

  1. first() is called → Stack: [first]
  2. Inside first, second() is called → Stack: [first, second]
  3. Inside second, third() is called → Stack: [first, second, third]

Then it shrinks in reverse:

  1. third() finishes → Stack: [first, second]
  2. second() finishes → Stack: [first]
  3. first() finishes → Stack: []

The Reverse-Order Pattern

Notice that third must complete before second can finish, and second must complete before first can finish. The stack grows upward as calls nest deeper, then shrinks back down as each function returns.

This visualization helps you understand execution flow and debug issues like infinite recursion (when the stack never stops growing).

Key Takeaway: Stack frames pile up as functions call other functions, then pop off in reverse order as each function returns—the last function called is the first to finish.