Advance JavaScript (DOM, BOM, Web API) / Asynchronous JavaScript

Call Stack

The call stack helps JavaScript keep track of “where it is” in the code — which function is running now and which one should run next.

🧠 What the Call Stack Does

  • It starts with a global execution context (your main script).

  • Every time a function is called, a new function execution context is added.

  • It works like a stack of plates → Last In, First Out (LIFO).


⚙️ How It Works (Easy Steps)

  1. Start script → JavaScript creates the global context and puts it on the stack.

  2. Function call → A new context is created and pushed on top.

  3. Function calls another → Another context is added on top.

  4. Function finishes → Its context is removed (popped off).

  5. When stack is empty → Program is done.


✴️ JavaScript call stack example

Let’s start with the following example:

function add(a, b) {
    return a + b;
}

function average(a, b) {
    return add(a, b) / 2;
}

let x = average(10, 20);

1️⃣ Start of Program

  • main() (global execution context) is created.

  • It is pushed onto the call stack.

2️⃣ main() Calls average()

  • A new execution context for average() is created.

  • It is pushed on top of main().

3️⃣ Inside average(), it Calls add()

  • add() function is invoked.

  • JavaScript pushes add() onto the stack (last-in).

4️⃣ add() Finishes Execution

  • add() returns a value.

  • Its execution context is removed (popped).

5️⃣ average() Finishes Execution

  • After receiving result from add(), it completes.

  • JavaScript pops average() off the stack.

6️⃣ main() Completes

  • main() finishes.

  • Global execution context is removed

➡️ The following picture illustrates the overall status of the Call Stack in all steps:


Stack Overflow

  • The call stack is a structure used by the JavaScript engine to keep track of function calls.

  • If functions keep calling themselves without ever stopping, the stack fills up.

  • Once it exceeds the maximum stack size, the engine throws a RangeError.

For example, when you execute a recursive function that has no exit condition, the JavaScript engine will issue a stack overflow error:

function fn() {
    fn();
}

fn();// stack overflow

🔍 Explanation:

  • The function fn() calls itself recursively.

  • There's no termination condition (base case), so it keeps calling itself infinitely.

  • Each function call is added to the call stack, a structure that keeps track of function calls.

  • Eventually, the call stack becomes too large, exceeding its size limit.

Uncaught RangeError: Maximum call stack size exceeded