The factorial of a non-negative integer n, denoted by n!, is the product of all positive integers less than or equal to n. For example, 5! = 5 * 4 * 3 * 2 * 1 = 120. The value of 0! is defined to be 1. In JavaScript, you can find the factorial of a number using a function that uses a for loop to multiply the number by each integer between itself and 1. Here’s an example of a factorial function:

function factorial(n) {
    let result = 1;
    for (let i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}
console.log(factorial(5)); // Output: 120

Another way to find the factorial of a number in javascript is by using recursion.

function factorialRecursion(n) {
    if (n === 0) {
        return 1;
    }
    return n * factorialRecursion(n - 1);
}
console.log(factorialRecursion(5)); // Output: 120

The first function uses a for loop to iterate through each integer between 1 and n and multiply it with the current value of result, which is initialized to 1. The second function uses recursion where it check base case if n is 0, if yes return 1 else return n* factorialRecursion(n-1)

Also Read:

Categorized in: