Our volunteers haven't translated this article into Català yet. Join us and help get the job done!
You can also read the article in English (US).
Message
Error: Out of stack space (Edge) InternalError: too much recursion (Firefox) RangeError: Maximum call stack size exceeded (Chrome)
Error type
What went wrong?
A function that calls itself is called a recursive function. Once a condition is met, the function stops calling itself. This is called a base case.
In some ways, recursion is analogous to a loop. Both execute the same code multiple times, and both require a condition (to avoid an infinite loop, or rather, infinite recursion in this case). When there are too many function calls, or a function is missing a base case, JavaScript will throw this error.
Examples
This recursive function runs 10 times, as per the exit condition.
function loop(x) {
if (x >= 10) // "x >= 10" is the exit condition
return;
// do stuff
loop(x + 1); // the recursive call
}
loop(0);
Setting this condition to an extremely high value, won't work:
function loop(x) {
if (x >= 1000000000000)
return;
// do stuff
loop(x + 1);
}
loop(0);
// InternalError: too much recursion
This recursive function is missing a base case. As there is no exit condition, the function will call itself infinitely.
function loop(x) {
// The base case is missing
loop(x + 1); // Recursive call
}
loop(0);
// InternalError: too much recursion