How to find factorial of a number in JavaScript?

Factorial of number is the product of all positive descending integers. Factorial of n is denoted by n!. For example -

4! = 4 * 3 * 2 * 1 = 24

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

Here, 4! is pronounced as "4 factorial", it is also called "4 bang" or "4 shriek".

In this article, we are calculating the factorial of a number using JavaScript. Here, we are using two ways to find the factorial. The first one is the iterative approach, and another one is the recursive approach.

Using Iterative approach

Here, we are iterating a loop over the sequence of numbers to get the factorial of a given number. Using this approach, the consumption of memory is less than the recursive implementation. But the code is lengthier than the recursive method.

Let's see an example of the same.

Example

In this example, there is a text field that requires a number and a button, which gives us the factorial of the entered number. We have to enter a number in the given textfield to find the factorial of that number. Then we need to click the given button named Factorial to get the result.

If we enter a negative number, then the program calculates the factorial of 0, which is 1.

Test it Now

Output

After the execution of the above code, the output will be -

How to find factorial of a number in JavaScript

After entering the number and clicking the given button, the output will be -

How to find factorial of a number in JavaScript

Now, we will see how to calculate the factorial using recursive method in JavaScript.

Using Recursive approach

In this approach, we are using recursion to calculate the factorial of a number. Here, we call same function again and again to get the factorial. Using recursion, we have to code less than the iterative approach.

Now, we will see an example of finding the factorial of number using recursion in JavaScript.

Example

Here there is a function fact(), which accepts a parameter num. It is a number for which we need to calculate the factorial. The function returns 1 when the value of num is 0.

In the output we will see a text field that requires number and a button which gives us the factorial of the entered number. We have to enter a number in the given textfield to find the factorial of that number. Then we need to click the given button named as Factorial to get the result.

Test it Now

Output

After the execution of the above code, the output will be -

How to find factorial of a number in JavaScript

After entering the number and clicking the given button, the output will be -

How to find factorial of a number in JavaScript




Latest Courses