Write a JavaScript Program to Find Factorial of Number Using Recursion

In mathematics, the factorial of a non-negative integer is the product of all positive integers less than or equal to that number.

For example, the factorial of 5 is 5 * 4 * 3 * 2 * 1 = 120.

In this tutorial, we will write a JavaScript program to find the factorial of a number using recursion.

Recursion is a technique in which a function calls itself until a specific condition is met. In our case, we will write a function that calls itself until the factorial of the given number is calculated.

Here is the JavaScript code to find the factorial of a number using recursion:

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

Let’s understand this code step by step.

We defined a function called factorial that takes one parameter num. In the first line of the function, we check if the value of num is equal to 0. If it is, then we return 1 because the factorial of 0 is 1.

If num is not equal to 0, then we call the factorial function recursively with num – 1 as the parameter.

This continues until num becomes 0, at which point the recursion stops and the final value of the factorial is returned.

Let’s test our factorial function with some sample inputs:

console.log(factorial(0)); // Output: 1
console.log(factorial(5)); // Output: 120
console.log(factorial(10)); // Output: 3628800

As we can see from the output, our factorial function is working correctly and giving us the expected results.

In conclusion, we can find the factorial of a number using recursion in JavaScript by defining a function that calls itself until the factorial is calculated.

The recursion stops when the input parameter becomes 0, and the final value of the factorial is returned.