Factorialize a Number in JavaScript

Sonya Moisset
iDevOI
Published in
2 min readNov 25, 2016

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 am going to explain how to do it with a recursive function.

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 1factorialize(5) should return 120factorialize(10) should return 3628800factorialize(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

Factorialize a Number Using Recursion

Here’s my solution, with embedded comments:

Here’s my solution, without comments:

I hope you found this helpful. This is part of my “How to Solve FCC Algorithms” series of articles on the Free Code Camp Algorithm Challenges, where I propose several solutions and explain step-by-step what happens under the hood.

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

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

Resources

--

--

Sonya Moisset
iDevOI

Senior Security 🥑 || GitHub 🌟 || ☁️ OpenUK Ambassador || 🎓 CAPSLOCK & CyberGirls Lead Mentor || 👩🏻‍💻 Epic Women in Cyber/Tech initiatives