How To Find The Factorial of A Number Using Recursion in JavaScript

Chidera Humphrey
2 min readDec 7, 2022

--

If you have done math in school, you will testify the fact that finding the factorial of a number is a common problem. Even when you start learning programming, you will most likely face the challenge of finding the factorial of a given number.

It is not really a difficulty problem, but it teaches you how to think — as most programming problems do.

In this article, I’m going to show you how to find the factorial of a number using recursion in JavaScript.

First,

What’s Recursion?

Recursion in programming simply means a function calling itself. The function at some point calls itself which eventually turns into a loop.

Recursive functions are useful to do repeated work such as flattening a nested array, finding factorial of numbers, opening sub folders within sub folders and lots more. If you have been working with higher order array functions, you should know that the reduce method is a recursive function.

Recursion always have a base case (condition when met, the function terminates). Without such, it will go into an infinite loop and probably crash your browser or system.

One of the benefits of using is its elegance though beginner programmers may find it a bit confusing.

What’s the factorial of a number?

Factorial of a whole number 'n' is defined as the product of that number with every whole number less than or equal to 'n' till 1.

Mathematically,

n! = n(n-1)(n-2)…

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

Enough of theory, let’s dive into the fun part. Coding!!!

The examples above are simplistic and don’t require much mental effort. Imagine if you were given n = 100, this will take you a considerable amount of time and can be very erroneous.

You can do this with JavaScript, here’s how

The “if” statement is the base case. If the number is 0, the function should return 1. Otherwise, the function should call itself with the new parameter, n, one less than the previous and multiplied by the previous value of n.

Conclusion

In this article, you have learned what recursion is and how to use it to find the factorial of a number.

Like and share if you found value in this post.

Also follow me for more easy-to-digest JavaScript tidbits like this.

Till we meet again, happy coding.

--

--