Chapter XIII · Call Stack

Stack Overflow

A stack overflow occurs when the call stack exceeds its maximum memory allocation limit, usually caused by infinite recursion.

01 How It Works

Think of piling boxes onto a small table until the entire tower collapses under weight limits.

Every nested function call adds a frame to the stack. Without an exit condition, stack frames accumulate until memory exhaustion.

example.js
function recurse() {
  recurse(); // Infinite recursive call without base case
}
recurse(); // RangeError: Maximum call stack size exceeded
  1. 1. Function calls itself continuously without a base case.

  2. 2. Stack memory fills up past browser/runtime limits.

  3. 3. Engine throws a RangeError exception.

02 Practical Example

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

practical.js
// Safe recursion with base case prevents stack overflow:
function countdown(n) {
  if (n <= 0) return;
  countdown(n - 1);
}
countdown(5);

Key Takeaway

Always ensure recursive functions have clear base case exit conditions to prevent stack overflows.

Related Concepts