Maximum Call Stack Size Exceeded in JavaScript

Learn why JavaScript throws maximum call stack size exceeded, how recursion causes it, and how to prevent the error with examples.

Published

Updated

Read time 2 min read

Reviewed byDeepak Prasad

Maximum Call Stack Size Exceeded in JavaScript

The maximum call stack size exceeded error appears when JavaScript runs out of room for nested function calls. The most common cause is recursion that never stops or a function loop that keeps calling itself without a base case.

This error is usually a RangeError, and it matters in recursion, event callbacks, and deeply nested logic. If you are comparing recursion techniques, JavaScript nested function and JavaScript recursion factorial are the related topics.

Tested on: Node.js v20.18.2. A short note after each runnable snippet describes what you should see in the console.


Method 1: Trigger the stack error with recursion

A recursive function without a base case keeps calling itself until the stack limit is reached.

javascript
function recurse() {
  recurse();
}

try {
  recurse();
} catch (error) {
  console.log("stack-error:", error.name);
}
Output

You should see one line logging stack-error: RangeError.

This is the classic failure mode behind the error.


Method 2: Add a base case

A base case gives the function a safe exit.

javascript
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

console.log("stack-safe:", factorial(5));
Output

You should see one line logging stack-safe: 120.

Use a base case whenever you write recursive JavaScript code.


Method 3: Limit nested calls in practice

Keeping the call chain shallow prevents stack overflow in normal code paths.

javascript
function stepOne() {
  return "ok";
}

function stepTwo() {
  return stepOne();
}

console.log("stack-chain:", stepTwo());
Output

You should see one line logging stack-chain: ok.

This pattern is safer than uncontrolled recursion when the data depth is unknown.


Summary

The maximum call stack size exceeded error in JavaScript usually comes from runaway recursion or too many nested function calls. Prevent it with a clear base case, shallow call chains, and careful recursion limits.


Official documentation

Steve Alila

Specializes in web design, WordPress development, and data analysis, with proficiency in Python, JavaScript, and data extraction tools. Additionally, he excels in web API development, AI integration, …