Three Ways to Factorialize a Number in JavaScript

Buildings | Matthew Wiebe | unsplash.com

This article is based on Free Code Camp Basic Algorithm Scripting “Factorialize a Number

In mathematics, the factorial of a non-negative integer n can be a tricky algorithm. In this article, I’m going to explain three approaches, first with the recursive function, second using a while loop and third using a for loop.

We have already seen a recursion approach on a String in the previous article, How to Reverse a String in JavaScript in 3 Different Ways ? This time we will apply the same concept on a number.


Algorithm Challenge

Return the factorial of the provided integer.
If the integer is represented with the letter n, a factorial is the product of all positive integers less than or equal to n.
Factorials are often represented with the shorthand notation n!
For example: 5! = 1 * 2 * 3 * 4 * 5 = 120

Provided test cases

  • factorialize(0) should return 1
  • factorialize(5) should return 120
  • factorialize(10) should return 3628800
  • factorialize(20) should return 2432902008176640000

What is factorializing a number all about?

When you factorialize a number, you are multiplying that number by each consecutive number minus one.

If your number is 5, you would have:

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

The pattern would be:

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

1. Factorialize a Number With Recursion

Without comments:


2. Factorialize a Number with a WHILE loop

Without comments:


3. Factorialize a Number with a FOR loop

Without comments:


“How to Solve FCC Algorithms” is a series of articles on the Free Code Camp Algorithm Challenges where I try to propose several solutions and explain step by step what happens behind the hood.

If you have your own solution or any suggestions, share them below in the comments.

Or you can follow me on Medium, Twitter, Github and LinkedIn, right after you click the green heart below ;-)

‪#‎StayCurious‬, ‪#‎KeepOnHacking‬ & ‪#‎MakeItHappen‬!