RangeError: Maximum Call Stack Size Exceeded
The function calls itself recursively too many times, exceeding the stack size limit.
Explanation
RangeError: Maximum call stack size exceeded occurs when a function calls itself (directly or indirectly) too many times, exceeding JavaScript's call stack size limit. This is the JavaScript equivalent of Python's RecursionError. Common causes include infinite recursion (function calling itself without a base case), circular references in object serialization, and deeply nested function calls. The default stack size varies by engine but is typically around 10,000-25,000 calls.
Common Causes
- Infinite recursion without base case
- Circular object references
- Deeply nested function calls
- Recursive call doesn't progress
- Event listener triggering itself
Solution
Add a base case to stop recursion. Verify recursive calls actually move toward the base case. Convert recursive algorithms to iterative ones using loops and explicit stacks. Use memoization to reduce redundant recursive calls. For circular reference issues, break the cycle before serialization. Use JSON.stringify with a replacer function to handle circular references. Consider using Tail Call Optimization (TCO) where supported.
Code Example
// Infinite recursion - no base case
function factorial(n) {
return n * factorial(n - 1); // RangeError!
}
// Fix: add base case
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1);
}
// Circular reference in serialization
const obj = {};
obj.self = obj; // circular!
JSON.stringify(obj); // RangeError!
// Fix: use replacer function
const seen = new WeakSet();
JSON.stringify(obj, (key, value) => {
if (typeof value === 'object' && value !== null) {
if (seen.has(value)) return '[Circular]';
seen.add(value);
}
return value;
});
// Convert to iterative
function factorialIterative(n) {
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
Error Information
Language
javascript
Difficulty
Intermediate
Views
129
Related Errors
Frontend
Webpack Module Not Found
Webpack cannot resolve a module or file imported in the code.
Frontend
ChunkLoadError
A dynamically imported JavaScript chunk failed to load from the server.
Frontend
React Key Warning
React warns that list items are missing unique "key" props for efficient rendering.
JavaScript
TypeError: X is not a function
The code tries to call a value as a function, but it's not a function.