🧩 Call Stack in JavaScript

Last Updated: 27th October 2025


The Call Stack is a data structure that keeps track of where the program is in its execution.
It tells JavaScript which function is currently running, and what to return control to when that function finishes.

Hinglish Tip 🗣: Call Stack ko ek “to-do list” samjho — JS ek time mein ek hi kaam karta hai, aur har kaam khatam hone ke baad agla kaam karta hai (LIFO: Last In, First Out).


🧱 How It Works

  • Whenever a function is called, it is pushed to the top of the stack.
  • When the function finishes, it is popped off the stack.
  • JavaScript executes code from top to bottom, one function at a time.

Example 1: Simple Stack Flow

function first() {
  console.log("First function");
}

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

second();

Step-by-step Execution (Stack Flow):

  1. second() is called → pushed to stack
  2. Inside it, first() is called → pushed to stack
  3. first() executes and completes → popped
  4. console.log("Second function") runs → second() completes → popped

Example 2: Nested Functions

function multiply(x, y) {
  return x * y;
}

function square(n) {
  return multiply(n, n);
}

function printSquare(num) {
  console.log(square(num));
}

printSquare(4);

Call Stack Flow:

printSquare(4)
 → square(4)
   → multiply(4,4)
     → return 16
   → return 16
 → console.log(16)

🧠 Important Notes

  1. Synchronous Execution:
    • JS runs code line-by-line, waiting for each task to finish before moving on.
  2. Stack Overflow:
    • If too many functions are pushed (like infinite recursion), stack memory fills up →
    • ⚠️ RangeError: Maximum call stack size exceeded
  3. Relation with Event Loop:
    • The Event Loop checks if the Call Stack is empty.
    • Only then it moves queued async tasks (like setTimeout) to be executed.