Uncaught RangeError: Maximum call stack size exceeded

I've noticed this error pop up a few times, and unfortunately, debugging it can sometimes be difficult.

Uncaught RangeError: Maximum call stack size exceeded 

While not always, typically I see this error within a recursive function.

What did I do to get this error?

Here's an example of how the error could occur:

function fibonacci(num){
    if (num === 1) 
    {
        return [0, 1]
    } 
    else 
    {
        var s = fibonacci(num - 1)
        s.push(s[s.length - 1] + s[s.length - 2])
        return s
    }
};

fibonacci(20000)[20000]

Why didn't it work?

  • The call stack is the list of all the different operations that have performed in order.
  • Recursive functions, by definition, call themselves in at least one logic branch (in this case, when num != 1).
  • Since this is a recursive function, calling this method 20,000 times caused the call stack to grow too large.

The solution

In the case of a recursive function causing this error, it's often best to re-write the logic so that it isn't recursive, or find some method of batching the recursion.

In this case, I re-wrote it so that it isn't recursive:

function fibonacci(num) {
    var a = 1, b = 0, temp

    while (num >= 0){
        temp = a
        a = a + b
        b = temp
        num--
    }

    return b
}

fibonacci(200000)

In short, recursive functions work great unless there are a few thousand iterations!