Understanding factorializing a number

function factorialize(num) {
  if (num === 0) { return 1; }
  return num * factorialize(num-1);
}

In these lines of code I am curious as to why { return 1; } is required to prevent a stack overflow?

Also, why would I set factorialize(num -1) instead of (num 0) in the return equation.?

  1. 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.
  2. 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.

1 Like

Thank you! This is much clearer, but I’m still not following a certain part.

I understand that in the if statement the return is acting as a conditional piece basically, but I’m not positive I understand why it must return 1. Is it returning 1 so that the equation doesn’t ever multiply itself by 0? Maybe its best I brush up on the basic lessons again haha… thank you for your help regardless!

it is because if you multiply something by 0, then it becomes 0, and because the factorial of 0 is 1

2 Likes