Chapter XIII · Call Stack

Call Stack

The call stack is a LIFO (Last-In, First-Out) data structure that tracks where the program is in its execution flow.

01 How It Works

Think of a physical stack of cafeteria trays: you add trays on top and remove them from the top.

When a function is called, its execution context is pushed onto the stack. When it returns, it is popped off.

example.js
function first() {
  second();
}
function second() {
  console.log("Inside second");
}
first();
  1. 1. Script execution starts, pushing Global Execution Context onto the stack.

  2. 2. Function calls push new execution contexts on top.

  3. 3. As functions complete, contexts are popped off sequentially.

02 Practical Example

Here is how you might see this concept applied in real-world code:

practical.js
function a() { b(); }
function b() { c(); }
function c() { console.log("Stack trace tracking"); }
a();

Key Takeaway

JavaScript is single-threaded with a single call stack, processing one execution context at a time.

Related Concepts