Function to compute factorial of a number in JavaScript

In this article, we will explore different methods to calculate the factorial of a number in JavaScript.

What is Factorial?

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, the factorial of 4 is 4 × 3 × 2 × 1 = 24, represented as 4!.

The value of 0! is defined as 1 by convention.

Mathematical Formula

The factorial of n is represented as n! and calculated using:

n! = n × (n-1) × (n-2) × ... × 3 × 2 × 1

Using For Loop

We can calculate factorial using a for loop by iterating from n down to 1.

Algorithm

  • Initialize a result variable with value 1

  • If number is less than 0, return -1 (factorial undefined for negative numbers)

  • If number equals 0, return 1

  • For numbers greater than 0, multiply result by each number from n down to 1

<!DOCTYPE html>
<html>
<head>
   <title>Factorial using For Loop</title>
</head>
<body>
   <button onClick="calculateFactorial()">Calculate Factorial</button>
   <p id="result"></p>
   
   <script>
      function calculateFactorial() {
         function factorial(num) {
            if (num < 0) {
               return -1;
            }
            else if (num === 0) {
               return 1;
            }
            else {
               let result = 1;
               for (let i = num; i > 1; i--) {
                  result *= i;
               }
               return result;
            }
         }
         
         const num = 5;
         const factorialResult = factorial(num);
         document.getElementById("result").innerHTML = `Factorial of ${num} is: ${factorialResult}`;
      }
   </script>
</body>
</html>
Factorial of 5 is: 120

Using Recursion

Recursion provides an elegant solution by calling the function itself with decremented values until reaching the base case.

Algorithm

  • If number is less than 0, return -1

  • If number equals 0, return 1 (base case)

  • Otherwise, return num × factorial(num - 1)

<!DOCTYPE html>
<html>
<head>
   <title>Factorial using Recursion</title>
</head>
<body>
   <button onClick="calculateRecursiveFactorial()">Calculate Factorial</button>
   <p id="recursiveResult"></p>
   
   <script>
      function calculateRecursiveFactorial() {
         function factorial(num) {
            if (num < 0) {
               return -1;
            }
            else if (num === 0) {
               return 1;
            }
            else {
               return num * factorial(num - 1);
            }
         }
         
         const num = 5;
         const result = factorial(num);
         document.getElementById("recursiveResult").innerHTML = `Factorial of ${num} using recursion: ${result}`;
      }
   </script>
</body>
</html>
Factorial of 5 using recursion: 120

Using While Loop

A while loop provides another iterative approach to calculate factorial.

Algorithm

  • Initialize result variable with the input number

  • Handle special cases: 0! = 1, 1! = 1

  • Use while loop to multiply result by decremented values

<!DOCTYPE html>
<html>
<head>
   <title>Factorial using While Loop</title>
</head>
<body>
   <button onClick="calculateWhileFactorial()">Calculate Factorial</button>
   <p id="whileResult"></p>
   
   <script>
      function calculateWhileFactorial() {
         function factorial(num) {
            if (num < 0) {
               return -1;
            }
            if (num === 0 || num === 1) {
               return 1;
            }
            
            let result = num;
            while (num > 1) {
               num--;
               result *= num;
            }
            return result;
         }
         
         const num = 5;
         const result = factorial(num);
         document.getElementById("whileResult").innerHTML = `Factorial of ${num} using while loop: ${result}`;
      }
   </script>
</body>
</html>
Factorial of 5 using while loop: 120

Comparison of Methods

Method Time Complexity Space Complexity Readability
For Loop O(n) O(1) Good
Recursion O(n) O(n) Excellent
While Loop O(n) O(1) Good

Conclusion

All three methods effectively calculate factorial with O(n) time complexity. Choose recursion for mathematical elegance, or iterative approaches (for/while loops) for better memory efficiency in large computations.

Updated on: 2026-03-15T23:19:00+05:30

13K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements