In this tutorial, let’s look at the different ways of finding the factorial of a number in JavaScript.
To start with, we’re going to look at the iterative approach, where we’ll be looking at using both the while and for loops. In the next section, let’s look at using recursive functions to achieve our purpose.
How to calculate factorial of a number?
To start with, if you’re not familiar with how factorial works, let me explain it to you before we start looking at how to achieve the result with code.
Factorial is usually written like this: n!
Here, n! means that we’d like to find the factorial of the positive, whole number ‘n. Notice how I said positive whole number?
Yes, that’s because factorials don’t work with negative numbers or decimal numbers, so that’s something you need to create checkpoints for in your code.
So, how’s it calculated? That’s very simple as well. Just start multiplying n with its decrements until you reach 1, and the result is the factorial of said number. Let me show you.
5! = 5 * 4 * 3 * 2 * 1 = 120
4! = 4 * 3 * 2 * 1 = 24
3! = 3 * 2 * 1 = 6
2! = 2 * 1 = 2
1! = 1 * 1 = 1
0! = 1 = 1
It’s quite simple as I promised, isn’t it? But look out for factorial of 0. You might think its 0 because anything multiplied by 0 is 0, but in this case, it’s actually 1.
Why is that? Well, since 0 has no value, and a factorial always ends with a multiplication of 1, we’re just left with 1 at the end, which is the result of 0!
So now that you know how factorials work, how can we achieve these results with code? There are 2 approaches. Let’s look at them both now.
Iterative approach to finding the factorial in JavaScript
One of the easiest ways to find the factorial of a number in JavaScript is by using the iterative approach.
As the name implies, you’re going to iterate from 1 through n using the available loops (while and for loops) and return the result. It’s as simple as that.
Using the While loop
Let’s start with the while loop. We’ve created an arrow function findFactorial that accepts an argument ‘n’, where n is the positive whole number you want to find the factorial of.
To start with, let’s create a variable factValue and assign it the base value of 1 (the last multiplied number in every factorial operation).
Now, let’s create our checkpoints. We’re going to look out for 3 things:
1. If our number is 0, then we can directly return 1.
2. If our number is negative, we can’t proceed
3. If our number is either a NaN value (Not an number) or a decimal value (not a whole number/integer), we can’t proceed. We use the isInteger method to check for both NaN and floating-point values at the same time. Unless the value is an integer, it’ll always return a false.
That’s it! Once the checkpoints are created, let’s just get on with our ‘while’ loop.
Let’s create an iterator ‘i’ and assign it an initial value of 1 (the base value for factorials).
The while loop is going to run until the value of ‘i’ reaches ‘n’. For every iteration of the loop, let’s multiply factValue by i and then increment it.
Finally, return factValue, as shown below:
//Iterative approach - while loop const findFactorial = (n) => { let factValue = 1; if(n === 0) return 1; if(n < 0 || !Number.isInteger(n)) return 'Please enter a valid number'; let i = 1; while(i <= n) { factValue *= i; i++; } return factValue; } console.log(findFactorial(5)); //5! = 5 * 4 * 3 * 2 * 1 = 120 console.log(findFactorial(0)); //0! = 1 console.log(findFactorial(1)); //1! = 1 console.log(findFactorial('a')); //'Please enter a valid number' console.log(findFactorial(4.2)); //'Please enter a valid number'
As you can see above, for 5, you get back 120. For 0 and 1, you get back 1. For ‘a’ and 4.2 (NaN and floating-point numbers), you get back ‘Please enter a valid number’. Our program works perfectly.
So, how does the iteration work here? Let’s go through it step by step:
1. For the first iteration of the loop (i = 1), factValue = 1 and factValue *= i would be factValue = 1 * 1 = 1
2. For the 2nd iteration (i = 2): factValue = 1 * 2 = 2
3. For the 3rd iteration (i = 3): factValue = 2 * 3 = 6
4. For the 4th iteration (i = 4): factvalue = 6 * 4 = 24
5. For the 5th and final iteration (i = 5): factValue = 24 * 6 = 120
That’s how the factorial is calculator using loops.
Using the For loop
Just like in the last section, let’s find the factorial using a ‘for’ loop. The only difference here is that you’re using a ‘for’ loop instead of a ‘while’ loop. The rest of the code logic remains the same, as shown below:
//Iterative approach - For loop const findFactorial = (n) => { let factValue = 1; if(n === 0) return 1; if(n < 0 || !Number.isInteger(n)) return 'Please enter a valid number'; for(let i = 1; i <= n; i++) { factValue *= i; } return factValue; } console.log(findFactorial(5)); //5! = 5 * 4 * 3 * 2 * 1 = 120
Recursive approach to finding the factorial of a number in JavaScript
Finally, let’s look at the recursive approach. Our findFactorial function starts off the same, except for one minor change. We’re not going to create factValue here.
Instead, we’re going to proceed with the checkpoints (when n is 0, negative, floating-point or NaN value).
Then, let’s create our recursive function. It’s quite simple. Earlier, we multiplied in ascending increments (from 1 to n).
Now, let’s multiple in descending increments (n to 1).
So, the recursive condition would be n * findFactorial(n – 1), as shown below:
//Recursive approach const findFactorial = (n) => { if(n === 0) return 1; if(n < 0 || !Number.isInteger(n)) return 'Please enter a valid number'; return n * findFactorial(n - 1); } console.log(findFactorial(5)); //5! = 5 * 4 * 3 * 2 * 1 = 120
So, how does this work really? Let me illustrate with an example.
Let’s take the above example of 5! for the purposes of this illustration. Let’s go through the steps of the recursion:
1. For the first recursion: return 5 * findFactorial (4);
2. For the second recursion: return 5 * 4 * findFactorial(3) = 20 * findFactorial(3);
3. For the third recursion: return 20 * 3 * findFactorial(2) = 60 * findFactorial(2);
4. For the fourth, and final recursion: return 60 * 2 * findFactorial(1) = 120 * findFactorial(1);
5. For the fifth, and final recursion: return 120 * 1 * findFactorial(0);
From the instructions given in the code 0 returns 1, so the final result would be:
return 120 * 1 * 1 = return 120;
That’s it! Those are the 3 different ways of finding the factorial of a given number in JavaScript.