How to Fix RangeError: Maximum call stack size exceeded in JavaScript
In this tutorial, you'll learn about How to Fix RangeError: Maximum call stack size exceeded in JavaScript. We cover key concepts, practical examples, and best practices.
The Problem
JavaScript throws RangeError: Maximum call stack size exceeded when a function calls itself recursively without a proper base case, overflowing the call stack.
Quick Fix
Step 1: Find the infinite recursion
A recursive function without a termination condition causes stack overflow:
function countdown(n) {
console.log(n);
countdown(n - 1);
}
countdown(5);
RangeError: Maximum call stack size exceeded
Add a base case to stop the recursion:
function countdown(n) {
if (n <= 0) return;
console.log(n);
countdown(n - 1);
}
countdown(5);
5
4
3
2
1
Step 2: Check for accidental circular references
Mutual recursion between two functions:
function a() { b(); }
function b() { a(); }
a();
RangeError: Maximum call stack size exceeded
Ensure at least one function has a condition to break the cycle:
let depth = 0;
function a() {
if (depth > 10) return;
depth++;
b();
}
function b() { a(); }
a();
Step 3: Convert recursion to iteration
Deep recursion can be replaced with a loop to avoid stack limits:
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
Iterative version:
function factorial(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
console.log(factorial(5));
120
Step 4: Increase stack size (Node.js)
If the recursion depth is legitimate and unavoidable, increase the stack size:
node --stack-size=10000 script.js
This is a workaround, not a fix. Prefer converting to iteration.
Prevention
- Always include a base case in recursive functions.
- Add a depth limit parameter to guard against infinite recursion.
- Prefer iterative solutions (loops) for deep traversals.
- Use tail recursion with proper optimization where available.
Common Mistakes with rangeerror
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - Forgetting
deriving (Show, Eq)on custom data types needed for debugging
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro