Calculating a factorial is very easy, but many JS implementations online make this problem unnecessarily complex. In this tutorial, we’ll see the basics of how to calculate a factorial in JavaScript. We’ll also go through the explanation of building a factorial calculating function in JS step-by-step.

The factorial of 5 is `1 * 2 * 3 * 4 * 5`. If you searched online, the different examples and implementations of how to calculate a factorial can seem pretty convoluted. Luckily, as most exercises in this book, it’s possible to simplify the solution, so that we can have better understanding of how to solve a particular exercise.

So, how do we go about writing a function that takes a number, a calculates its factorial? An obvious way to begin would be to write a function declaration:

Now we need to think through how to solve this task. The first observation is: the passed in number is the highest number to multiply with. In other words, if we pass in the number 5, the remaining numbers to multiply with are 4, 3, 2, and 1. This looks a lot like a loop, so let’s add it in:

Great, we’re logging out the value of `i`. Now we need to multiply our numbers. The trick here is to add another variable, which we’ll use as an aggregator. Initially, the variable’s value will be `1`. Next, we’ll update it by multiplying it with the current loop’s value of `i`. In our example above, that resolves to:

Let’s update our code:

Here’s our code, cleaned up a bit:

That’s it! All the other implementations are just a variation of this basic idea. Most of the time, they’re unneccessary complications.

For example, we can replace the `for` loop, with a `while` loop:

While in the `for` loop, the countdown was set up with the temporary `i` variable of the `for` loop, in the above solution, the countdown is contained in the `num = num - 1`. This is very important, because without an exit condition, it’s easy for a `while` loop to become an infinite loop.

Note:
This exercise comes from Book 3 of my book series on JS, available on Leanpub.com.