Factorial of a Number in JavaScript

In this example, you will learn how to write a JavaScript program to calculate the factorial of a number.

Basically, we are going to learn different ways to calculate the factorial of a number in JavaScipt.

The factorial of a number is the product of all the numbers from 1 to that number. For example,

factorial of 5 is equal to 1 * 2 * 3 * 4 * 5 = 120.

The factorial of a positive number n is given by:

factorial of n (n!) = 1 * 2 * 3 * 4.....n

The factorial of negative numbers do not exist and the factorial of 0 is 1.

JavaScript Program to Find the Factorial of a Number

Three ways to calculate the factorial of a number in JavaScript:

  1. With recursion
  2. With a while loop
  3. With a for loop

main.js

Let's create a main.js file and add the following code to it:

// 1. With recursion

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



// 2. With a while loop
function factorializeUsingWhileLoop(num) {
  var result = num;
  if (num === 0 || num === 1) 
    return 1; 
  while (num > 1) { 
    num--;
    result *= num;
  }
  return result;
}



// 3. With a for loop
function factorializeUsingForLoop(num) {
  if (num === 0 || num === 1)
    return 1;
  for (var i = num - 1; i >= 1; i--) {
    num *= i;
  }
  return num;
}


// TESTINT
console.log("Factorial of 5 -> " + factorializeUsingRecursion(5));
console.log("Factorial of 6 -> " + factorializeUsingWhileLoop(6));
console.log("Factorial of 7 -> " + factorializeUsingForLoop(7));

Note that the comments in the above code are self-descriptive.

index.html

To test JavaScript code, let's create an HTML file named index.html and add the following code to it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <script src="main.js"></script>
</body>
</html>

Note that we have included the main.js file as an external JavaScript file:

<script src="main.js"></script>

Run index.html in Browser

Run above index.html file in browser and open dev tools console to see the output of the JavaScript code:

Factorial of 5 -> 120
Factorial of 6 -> 720
Factorial of 7 -> 5040

Related JavaScript Examples

Comments