Write a JavaScript Program to Find the Factorial of a Number

In mathematics, factorial is a function represented by an exclamation mark (!) that takes a positive integer as input and returns the product of all positive integers up to and including that integer. For instance, the factorial of 5 is 5 x 4 x 3 x 2 x 1, which equals 120.

In JavaScript, we can write a program to find the factorial of a number using a loop or recursion. Let’s first look at the loop solution.

Loop solution:

function factorial(num) {
let result = 1;
for (let i = 2; i <= num; i++) {
result *= i;
}
return result;
}

console.log(factorial(5)); // output: 120

Explanation:

We declare a variable result and set it to 1, as any number multiplied by 1 is itself.

We then use a for loop to iterate from 2 up to the input number num, multiplying result by each number in the loop.

Finally, we return result.

Recursion solution:

function factorial(num) {
if (num === 0) {
return 1;
} else {
return num * factorial(num - 1);
}
}

console.log(factorial(5)); // output: 120

Explanation:

We define a function factorial that takes a number num as input.
If num is 0, we return 1, as 0! is defined as 1.
If num is not 0, we return num multiplied by the factorial of num – 1.
The function calls itself recursively until it reaches the base case of 0.

In conclusion, the above JavaScript programs provide two solutions to find the factorial of a number. Depending on the situation, you can choose the one that suits you better.