JavaScript Program To Find Factorial Of A Number


In this tutorial, you’ll learn how to write a program to find factorial of a number. This post is a part of the JavaScript coding practice series.

Factorial Of A Number

First, let’s try to understand what the factorial means before trying to implement it.

The factorial of a number n means, the product of all positive integers less than or equal to n. For example, the factorial of 4 is 4*3*2*1 = 24.

Implementing Factorial Of A Number

Let’s start by creating a JavaScript function to get factorial of a number. The function accepts a parameter called n for which you need to calculate the factorial.

Since the factorial of 0 and 1 is 1, let’s check for number above 1. Let’s loop from >1 to <=n and keep calculating the product of numbers <= n. Using this logic here is how the factorial function turns out :

    function factorial(n) {
        /* let's initialize the fact variable to 1*/
        let fact = 1;
    
        /* let's loop only if the n is > 1 else  return result 1*/
        if(n > 1) {
            for(let i = 2; i <= n; i++) {
                fact *= i;
            }
        }
        return fact;
    }
    
    console.log(factorial(4))
    // outputs 24
    console.log(factorial(0))
    // outputs 1
    console.log(factorial(1))
    // outputs 1