JavaScript

# How to Find the Factorial of a Number in JavaScript

In programming languages, factorials determine the product of numbers that are less or equal to a particular number. Beside this, it plays an effective role in mathematics to calculate numbers in a large range. More specifically, in JavaScript, you can find the factorial of a number with various methods such as by using the iterative approach and recursive approach.

This post will explain about finding the number’s factorial in JavaScript.

## How to Find/Calculate the Factorial of a Number in JavaScript?

There are various approaches available for finding the number’s factorial with the help of JavaScript. Some of them are listed below:

## Method 1: Find/Calculate the Factorial of a Number Utilizing the Iterative Approach

For calculating the number’s factorial by utilizing the iterative approach, check out the stated instructions:

• First of all, define a function by using a particular name. To do so, we have defined the function as “fact()” that accepts an integer “number” as an argument.
• Next, define a variable with a specific name according to your choice and assign a value to that variable.
• This function uses the “for” loop for iterating the number within the range and multiplies the result by each number in the range.
• After that, return the factorial as a value with the help of the “return” statement:
function fact(number) {
let factorial = 1;
for (var i = number; i > 1; i--) {
factorial *= i;
}
return factorial;
}

Lastly, call the function to calculate the factorial of the passed number:

fact(21); It can be observed that the factorial of the specified number has been calculated successfully.

## Method 2: Find/Calculate the Factorial of a Number Utilizing the Recursive Approach

Factorial of the number can also be calculated by the recursive approach. To do so, we will use the if-else condition.

For practical implications, follow the given code snippet:

• Define a function with a name.
• Utilize the “if-else” condition that implies, if the passed number is equal to 1, then it will return 1 otherwise the stated factorial formula will calculate the value and return it to the console:
function fact(num) {
if (num == 1)
return 1;
else {
return (num * fact(num - 1));
}
}

Now, calculate factorial by calling the function and pass the number “9” as argument:

fact(9); That was all about calculation and finding the number’s factorial with the help of JavaScript.

## Conclusion

To find the factorial of a number, two methods can be utilized. The first method is the “Iterative Method” and the second one is the “Recursive Method”. To do so, the iterative method utilizes the simple loop whereas the recursive method depends on the “for” loop. This post stated the multiple methods for finding or calculating the factorial of a number in JavaScript. 