Find the Factorial of a Number in JavaScript

This is a preview lesson
Register or sign in to take this lesson.

This tutorial shows how to find the factorial of a number in JavaScript. In JavaScript, we can use for loop and if…else if statement.

For a given non negative number, n, the factorial of the number can be calculated as:

factorial(n) = n * (n-1) * ... * 1

Example 1 : Find Factorial of a Number.

//program to find the factorial of a number

function findFactorial(num){
  let factorial = 1;
  if(num < 0){
      return factorial = "Invalid Number !"
  }
  else if (num == 0 || num == 1){
    return factorial;
  }
  else{
    for(let i = num; i >= 1; i--){
      factorial = factorial * i;
    }
    return factorial;
  }  
}
console.log(findFactorial(1));
console.log(findFactorial(5));
console.log(findFactorial(-2));

Output

1
120
Invalid Number !