PromptHub
JavaScript Intermediate 10 views

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

10

Related Errors