In functional programming , it is very common to use functions recursive . Certain languages, such as Scheme, do not even have control structures for loops, depending on recursion to iterate over lists.
JavaScript has functional features, such as first-class functions, but has restrictions on how to use recursion. For example:
function fatorial(num) {
if (num === 0) {
return 1;
}
return num * fatorial(num - 1);
}
fatorial(5); // 120
fatorial(100000); // RangeError: Maximum call stack size exceeded
Please ignore the fact that fatorial(100000)
is a number that JavaScript is not even able to represent.
If the number of recursions exceeds a certain limit, the engine is not able to process the result, throwing an error or crashing the program. This is because the call stack size (which stores the execution context of each invocation of the function - which includes local variables and the reference to the "parent" scope of the function, the basis of the closures ) has a fixed size. And this limit exists to ensure that the call stack does not consume excess memory.
There is, however, a technique to avoid this limitation, depending on how the function code is structured. If the recursive call is in