Calculate Factorial With JavaScript - Iterative and Recursive

# Calculate Factorial With JavaScript - Iterative and Recursive

### Introduction

A factorial of a number is the product of that integer and all the positive integers that are lesser than or equal to it. It has to be a positive integer - otherwise, the logic extends to negative infinity. In other words - calculating a factorial means multiplying all whole numbers between a number and 1.

0! equals 1, by convention, and doesn't follow the standard rule.

A factorial is denoted by the integer we're calculating a factorial for, followed by an exclamation mark.

5! denotes a factorial of five.

And to calculate that factorial, we multiply the number with every whole number smaller than it, until we reach 1:

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


In this tutorial, we will learn how to calculate the factorial of an integer with JavaScript, using loops and recursion.

### Calculating Factorial Using Loops

We can calculate factorials using both the while loop and the for loop. We'll generally just need a counter for the loop's termination and the supplied number we're calculating a factorial for.

Let's start with the for loop:

function getFactorialForLoop(n) {
let result = 1;
if (n > 1) {
for (let i = 1; i <= n; i++) {
result = result * i;
}
return result;
}
else {
return "n has to be positive";
}
}


You've probably been able to observe that we're starting the count at 1, not n - even though the definition of a factorial states that we go from n to 1. Though, mathematically, these are equivalent statements:

$$1 * 2 * 3 * 4 ... * n = n * (n-1) * (n-2) * (n-3) * (n-4) ... * (n - (n-1))$$

To simplify, (n - (n-1)) will always be equal to 1.

That means that it doesn't matter in which direction we're counting. It can start from 1 and increase towards n, or it can start from n and decrease towards 1. Now that that's clarified, let's take a look at what happens in this method.

It accepts n, the number we're calculating a factorial for. A value of 1 is assigned to a placeholder result variable, that will eventually be updated.

Why assign 1 and not 0 or other blanks?

If we were to assign 0 to it - all of the following multiplications would be with a 0. This ends up with just a 0 at the end.

Then we start our for loop with defining i as the counter that starts from 1. Notice that the condition statement is i <= n; in order to include the n itself as well.

Inside the for loop, we multiply the current value of result with the current value of our index i - performing the operation from the definition in reverse.

Finally, we return the final value of the result as the output of the method. Let's test our function in our browser's console and print out the result. Be sure to enter the factorial function in the browser's console first:

var inp = window.prompt("Enter a number: ");
inp = parseInt(inp);

alert("The result is: " + getFactorialForLoop(inp));


It will prompt the user to give input. We'll try it with 4. When you run the alert script, you'll see a popup with the result:

24


You can use a calculator to verify the result:

4! is 4 * 3 * 2 * 1, which results 24.

Now let's see how we can calculate factorial using the while loop. Here's our modified function:

function getFactorialWhileLoop(n){
let result = 1;
while (n > 1) {
result = result * n;
n -= 1;
}
return result;
}


This is pretty similar to the for loop. Except for this time we're moving from n towards the 1 - closer to the mathematical definition. Let's test our function:

## Free eBook: Git Essentials

Check out our hands-on, practical guide to learning Git, with best-practices, industry-accepted standards, and included cheat sheet. Stop Googling Git commands and actually learn it!

var inp = window.prompt("Enter a number: ");
inp = parseInt(inp);

alert("The result is: " + getFactorialWhileLoop(inp));


Like before, if we enter 4 we get 24. The calculation was 4*3*2*1 and the final result is the same as before.

Factorials are recursive in nature, and using recursion is a more natural approach to repeating an operation such as this multiple times.

### Calculating Factorial Using Recursion

A recursive function is a function that calls itself. It may sound a bit intimidating at first but bear with us and you'll see that recursive functions are easy to understand.

In general, every recursive function has two main components: a base case and a recursive step.

Base cases are the smallest instances of the problem - that's what repeats. Also a break, a case that will return a value and will get out of the recursion. In terms of factorial functions, the base case is when we return the final element of the factorial, which is 1.

Without a base case or with an incorrect base case, your recursive function can run infinitely, causing an overflow.

Recursive steps - as the name implies- are the recursive part of the function, where the whole problem is transformed into something smaller. If the recursive step fails to shrink the problem, then again recursion can run infinitely.

Consider the recurring part of the factorials:

• 5! is 5 * 4 * 3 * 2 * 1.

But we also know that:

• 4 * 3 * 2 * 1 is 4!.

In other words 5! is 5 * 4!, and 4! is 4 * 3! and so on.

So we can say that n! = n * (n-1)!. This will be the recursive step of our factorial!

A factorial recursion ends when it hits 1. This will be our base case. We will return 1 if n is 1 or less, covering the zero input.

Let's take a look at our recursive factorial function:

function getFactorialRecursively(n){
if (n <= 1){
return 1;
}
else{
return n * getFactorialRecursively(n-1);
}
}


As you see the if block embodies our base case, while the else block covers the recursive step.

Let's test our function:

var inp = window.prompt("Enter a number: ");
inp = parseInt(inp);

alert("The result is: " + getFactorialRecursively(inp));


We will enter 3 as input this time, and the alert will print 6 as the result.

We get the same result. But this time, what goes under the hood is rather interesting:

You see, when we enter the input, the function will check with the if block, and since 3 is greater than 1, it will skip to the else block. In this block, we see the line return n * getFactorialRecursively(n-1);.

We know the current value of n for the moment, it's 3, but getFactorialRecursively(n-1) is still to be calculated.

Then the program calls the same function once more, but this time our function takes 2 as the parameter. It checks the if block and skips to the else block and again encounters with the last line. Now, the current value of the n is 2 but the program still must calculate the getFactorialRecursively(n-1).

So it calls the function once again, but this time the if block, or rather, the base class succeeds to return 1 and breaks out from the recursion.

Following the same pattern to upwards, it returns each function result, multiplying the current result with the previous n and returning it for the previous function call. In other words, our program first gets to the bottom of the factorial (which is 1), then builds its way up, while multiplying on each step.

Also removing the function from the call stack one by one, up until the final result of the n * (n-1) is returned.

This is generally how recursive functions work. Some more complicated problems may require deeper recursions with more than one base case or more than one recursive step. But for now, this simple recursion is good enough to solve our factorial problem!

### Conclusion

In this article, we covered how to calculate factorials using for and while loops. We also learned what recursion is, and how to calculate factorial using recursion.

If you've enjoyed the recursion and want to practice more, try calculating the Fibonacci sequence with recursion! And if you have any questions or thoughts about our article, feel free to share in the comment section.

Last Updated: August 20th, 2021

Get tutorials, guides, and dev jobs in your inbox.