Looking into the SICP book and JS functional programming I created two recursive functions. My expectation was that both of them raised a stack overflow error. But it is only the sumAll() function that raised the error. See below the code for both functions sumAll() and factorial():
As expected the sumAll() function did raise a stack overflow error
function sumAll(n, i = 0, result = 0) {
return (i > n)
? result
: sumAll(n, i + 1, i + result);
}
console.log(sumAll(10000));
The factorial() function below did not raise a stack overflow error:
function factorial(n){
return (n == 1)
? 1
: n* factorial((n-1))
}
console.log(factorial(10000))
My question is why the factorial() function does not raise a stack overflow and works perfectly in nodeJS meanwhile the sumAll() did raise it also in nodeJS
factorialwill also throw a stack overflow if you raise the number from 10,000. It's not immune to a stack overflow, it just happens to be below the limit right now. I'm not sure whysumAllis reaching the limit, despite apparently recursing the same number of times.function sumAll(n) {return (n == 0) ? 0 : n + sumAll(n - 1);}-- a restructuring of thesumAllfunction to look like the factorial one. I know there are some v8 folks around here who are good at answering these, but I can't recall any handles ATM.