This is not a loop right?
Nope, it is not. It is a recursive function, a function that calls itself until a certain condition is met. In this case, is when num
is equals to 0.
Why does the function call itself continuously?
Because the function is called in the return value of this function. It will continue calling the function itself, until num equals 0. In which case the function will exit and return 1.
How does it know when to stop?
The condition if (num === 0)
. The variable num
gets subtracted if num isn't equal to 0 as stated in the code return num * factorialize(num-1);
. Notice that the function returns fresh function call but with the parameter num - 1
. When num
becomes 0. The function returns 1.
Wouldn't it just continue to factorialize negative numbers to
infinity?
Because we have this if (num === 0)
condition. So the num
parameter decreases each time the code return num * factorialize(num-1);
gets called, and eventually the above condition gets fulfilled and the function exits.
We can break it down step by step:
- factorialize(10) gets called.
- num is not 10, so return
num * factorialize(num - 1)
. In this case num is 10 and num - 1 is 9, so we are actually returning the following: 10 * factorialize(10 - 1)
.
- factorialize(9) gets called, then repeat step (1) and (2) until you get factorialize(0).
- When you reach factorialize(0), it will return 1. So the whole function effectively returns 10 * 9 * 8 * ... 1 * 1.
Makes sense?