Using recursion in Factorialize a Number (SOLVED)

Here’s the coding I’m trying to understand:

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

factorialize(5);

Here’s what I think is happening

  1. 5 is num, and gets passed to the function.

  2. 5 === 0 is false, so return 5 * factorialize(4)

  3. 4 is num, and we then get return 4 * factorialize(3)

Several steps like the ones shown above later:
num is 1 and so return * factorialize(0). After this step (because of the base case), we get return 1.

But where do we get the number 120? I don’t see something like let total = 1 to collect all these numbers, so where am I getting 120?

Look what you wrote for number 2:

return 5 * factorialize(4)

So you know you are going to return the number 5 multiplied by the result of factorialize(4). In number three that result is

return 4 * factorialize(3)

So now going back to number 2 you are returning:

5 * 4 * factorialize(3)

Do you see the pattern here?

2 Likes

Thank you! The way you phrased it made it make much more sense. I’ll have to save this explanation whenever I encounter recursion again.

By the way, in the real programming world, would this example be used or would something like this be used? The recursion way of solving it (in my opinion) seemed a little too over-the-top for something that’s more simple:

function factorialize(num) {
  for (var product = 1; num > 0; num--) {
    product *= num;
  }
  return product;
}

factorialize(5);

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.