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

Stack Overflow Errors

Recursion or infinite call chains can exceed the stack size limit, causing a "Maximum call stack size exceeded" error.

Stack Overflow Errors

What you'll learn: How recursion or infinite call chains can crash your program by exceeding the call stack's size limit.

The Stack Has a Limit

Remember that the call stack operates on a LIFO (Last In, First Out) principle, storing stack frames for each function call. But here's the catch: the stack has a maximum size. It's like a physical stack of plates — you can only pile them so high before the tower collapses.

When you call functions that keep adding frames to the stack without removing them (popping them off), you eventually hit this limit. JavaScript throws a "Maximum call stack size exceeded" error, commonly known as a stack overflow.

Common Causes

Infinite Recursion

The most common culprit is a recursive function that never reaches its base case:

function countForever(n) {
  console.log(n);
  countForever(n + 1); // Never stops calling itself
}

countForever(1); // RangeError: Maximum call stack size exceeded

Each call to countForever adds a new frame to the stack, but none ever complete and get removed.

Mutual Recursion Loops

Two functions calling each other indefinitely:

function first() {
  second();
}

function second() {
  first();
}

first(); // Stack overflow!

The Analogy

Think of the call stack like a narrow stairwell. Each function call is climbing up one step. If you keep climbing without ever coming back down (completing functions), you'll eventually hit the ceiling. That ceiling is the stack size limit.

How to Avoid Them

Always ensure recursive functions have a proper base case that stops the recursion, allowing stack frames to be popped off as functions complete.

Key Takeaway: Stack overflow errors occur when too many function calls accumulate on the stack without completing, most commonly from infinite recursion or circular function calls without proper termination conditions.