arrow_backBack to Blog

JavaScript Program to Find Factorial of a Number

Factorial of a positive number n is defined by product of all the numbers starting from 1 to n (both inclusive).

What is Factorial?

Factorial of a positive number n is defined by product of all the numbers starting from 1 to n (both inclusive).

Syntax

n! = n*(n-1)*(n-2)*…1

Factorial of 0 is 1.

Factorial of a negative number cannot be defined.

There are 2 ways to calculate factorial of a number.

Iteration

In this approach, we iterate through all the element from 1 to n and accumulate the product of element.

Syntax

n! = n*(n-1)*(n-2)*…1

Example

function factorial(n) {
    if (n < 0) {
        console.error('invalid number') return;
    }
    let result = 1;
    for (let i = 1; i <= n; i++) {
        result = result * i;
    }
    return result;
}
console.log(factorial(6))

Output

720

Using Recursion

In this approach we multiply the number with factorial of that number reduced by 1.

Syntax

n! = n*(n-1)!

Example

function factorial(n) {
    if (n < 0) {
        console.error('invalid number') return;
    }
    if (n === 1) {
        return 1
    }
    return n * factorial(n - 1);
}
console.log(factorial(6))

Output

720