FCC Bonfire Series 104: Factorialize a Number

Things are starting to GET (-unfunny reference-) interesting little by little. This time, we must write a function that takes a number, and returns the result of factorializing said number, welcome to: factorialize a number. (It’s factorize, excuse my engrish).

The factorial of a number (expressed in mathematics as x!) is calculated as the multiplication of every integer between our number and 1. Let me illustrate:

5! = 5 * 4 * 3 * 2 * 1 = 120

10! = 10 * 9 * 8 * 7 * 6 * 5 * 4 * 3 * 2 * 1 = 3628800

Simple enough right? So, how do we approach the problem. How can we automate this process and have a JavaScript functionm do all the work for us? The first solution that comes to mind is pretty intuitive:

function factorialize(num){
  var result = num;
  while (num > 1) {
    result = result * num;
  return result;

And you know what? It does what we need, and it work very well. But the obscure mind of a developer must take it farther into the world of the abstract. And there are fewer things more abstract that recursive functions. Recursive functions are functions that call themselves inside their execution context. You read that right, they call themselves. Here is an example:

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

That’s better. Right now, depending on your programming experience, you may be:

  1. Nodding.
  2. Wondering what the heck is going on.

If you fall inside of 2, I’m going to go bit by bit and explain what the code does to you. I might not be the best teacher, but bear with me, I’m trying my best.

Lets assume we call our factorialize function using the number 5: factorialize(5) . The function first checks if the variable num  is equal to 5 and since it isn’t, it goes right to the else statement. What we see here seems more complex than what it actually is. If num is equal to 5, this line gets converted to:

return 5 * factorialize(5 – 1);

Which is equal to return 5 * factorialize(4);

And if we follow the same steps we took previously to evaluate factorialize(5), we may assume that factorialize(4) will have the following return statement:

return 4 * factorialize(4 – 1);  or return 4 * factorialize(3);

And the chain keeps going and going like so:

return 3 * factorialize(2);

return 2 * factorialize(1);

At which poing, the function will return the value 1, because the if (num === 1) statement will be true. So what our magical line really does is the following:

return 5 * (4 * (3 * (2 * 1)));

Which is the same as 5 * 4 * 3 * 2 * 1 . It may not be intuitive. It may look abstract and hard to understand. But if you deeply understand what’s going on, you’ll be on the right track to JavaScript mastery, I can guarantee that.

Stay sharp and experiment with the code, it will help you understand!