Why is the maximum call stack size exceeded
when attempting to apply this simple factorial function to a negative number?
function factorial(n) {
if (n == 0) {
return 1
}
return n * factorial(n - 1)
}
I understand that factorial functions are meant for non-negative integers, but I'm wondering what is happening internally/in a JavaScript engine when this function is called on e.g. -1
.
It runs infinetly because (n == 0) doesnt met
if you pass a negative number
return n * factorial(n - 1)
invokes factorial function with more negative number recursively and thereby (n == 0) condition doesn't met