- It runs the function over and over again, with
num
going down by 1 each time: if you don’t have the exit condition, the number will just keep going down by 1 every time.
- If you put 0 in there, then
num
will be 0, so the function will just hit the exit condition immediately and exit.
factorialise(3)
is like
factorialise(3 * factorialise(2 * factorialise(1 * factorialise(0))))
factorialise(0)
returns 1, so it’s like
factorialise(3 * factorialise(2 * factorialise(1 * 1)))
That’s like
factorialise(3 * factorialise(2 * 1))
That’s like
factorialise(3 * 2)
That’s 6.
The function keeps running until it returns a concrete value (when n is 0, return 1), and then the stack of functions unwinds all the way back up to the top from there. If there isn’t an exit condition, it’ll just keep running forever.
It’s like this:
function factorialise(n) {
result = n
for (n; ; n--) {
result *= n - 1;
}
return n;
}
The empty condition in-between the two semicolons isn’t a mistake there, I’ve just missed out the end condition on the for loop. Every time it runs, it reduces n by one and multiplies that value - 1 by the current result. It will crash the browser eventually because, like a recursive function with no exit condition, it has nothing telling it when to stop.