Factorial Fun explainer


#1

The aim of this puzzle: Use a function that calls itself recursively.

Walkthrough of the solution:
The function factorial() takes a number as an argument, and returns the product of every number up to that number. For example, factorial(5) will return 120, as 5 * 4 * 3 * 2 * 1 = 120.

To complete the puzzle, change the code block inside the else statement from return number * factorial(number) to return number * factorial(number - 1).

Let’s take a look inside the function to see how it works.

Inside the function is an if…else statement. The if statement tests if the number passed into the function is less than or equal to 1. If this is true, the function will return 1. However, if the number is greater than 1, the code in the else block will run.

Inside the else block is where things get a bit tricky. The function will take the number, and multiply it by the result of calling the function again, this time with number - 1 as an argument.

This will make more sense if we follow a number through the function. Let’s try calling the function with 3 as an argument: factorial(3):

The if statement will check if 3 is less than or equal to 1. Because 3 is greater than 1, the code in the else block will run instead. This will return 3 * factorial(2).

The equation is now 3 * factorial(2).

The if statement will check the number again to see if 2 is less than or equal to 1. This is still false, so the else block will run, this time returning 2 * factorial(1), calling the function again with 1 as the number argument.

Our equation is now 3 * 2 * factorial(1)

When the function runs again with 1 as the number, the if statement code block will run, because 1 is less than or equal to 1. This code block simply returns the number, and the function can stop calling itself. This is important, as calling a function recursively without a condition that stops the function will make the recursion endless, and will cause a program to crash. sumUpTo(1) returns 1, and stops the function.

Our final equation is 3 * 2 * 1, which equals 6.

It can also be visualized like this:

factorial(3) → (3 * factorial(2))
                    factorial(2) → (2 * factorial(1))
                                        factorial(1) → 1

Which simplifies to:

factorial(3) → (3 * (2 * (1) ) ) 

Sample code solution:
(Tap below to reveal)

function factorial(number) {
  if (number < 1) {
    return 1;
  } else {
    return number * factorial(number - 1);
  }
}

console.log(factorial(5));

JavaScript Concepts: Recursion, Functions, Control Flow, If…Else Statements