Factorial Program in JavaScript

Introduction

The factorial of a number is the product of all positive integers less than or equal to that number. In JavaScript, you can compute the factorial using various methods such as recursion, iteration, and higher-order functions. This guide will walk you through different ways to compute the factorial in JavaScript.

Problem Statement

Create a JavaScript program that:

  • Accepts a positive integer.
  • Calculates and returns the factorial of that number using different methods.

Example:

  • Input: 5

  • Output: 120

  • Input: 3

  • Output: 6

Solution Steps

  1. Read the Input Number: Accept or define the number directly in the program.
  2. Handle Base Case: Return 1 if the input number is 0 or 1.
  3. Calculate Factorial: Implement different methods (recursion, iteration, functional programming).
  4. Display the Result: Output the calculated factorial for each method.

Method 1: Recursive Approach

// JavaScript Program to Find the Factorial of a Number Using Recursion
// Author: https://www.javaguides.net/

function factorialRecursive(n) {
    if (n === 0 || n === 1) {
        return 1;
    }
    return n * factorialRecursive(n - 1);
}

let number = 5;
let result = factorialRecursive(number);
console.log(`The factorial of ${number} using recursion is: ${result}`);

Output:

The factorial of 5 using recursion is: 120

Explanation:

  • This function uses recursion to calculate the factorial. The base case returns 1 for 0! and 1!. For other numbers, it recursively multiplies the number by factorial(n-1).

Method 2: Iterative Approach

// JavaScript Program to Find the Factorial of a Number Using Iteration
// Author: https://www.javaguides.net/

function factorialIterative(n) {
    let result = 1;
    for (let i = 2; i <= n; i++) {
        result *= i;
    }
    return result;
}

result = factorialIterative(number);
console.log(`The factorial of ${number} using iteration is: ${result}`);

Output:

The factorial of 5 using iteration is: 120

Explanation:

  • The iterative approach uses a for loop to calculate the factorial. It starts from 1 and multiplies by each subsequent number until it reaches n.

Method 3: Using Higher-Order Functions (Array reduce)

// JavaScript Program to Find the Factorial of a Number Using Array reduce
// Author: https://www.javaguides.net/

function factorialUsingReduce(n) {
    if (n === 0 || n === 1) {
        return 1;
    }
    return [...Array(n).keys()].map(i => i + 1).reduce((acc, val) => acc * val, 1);
}

result = factorialUsingReduce(number);
console.log(`The factorial of ${number} using reduce is: ${result}`);

Output:

The factorial of 5 using reduce is: 120

Explanation:

  • This method leverages JavaScript’s Array.reduce() to calculate the factorial. An array from 1 to n is created and then reduced by multiplying each element.

Conclusion

This JavaScript program demonstrates three methods to calculate the factorial of a number:

  1. Recursion is elegant but can be less efficient for large numbers due to stack overflow risks.
  2. Iteration is straightforward and memory efficient.
  3. Array reduce provides a functional programming approach, making the code concise and leveraging JavaScript’s higher-order functions.

Each method has its own advantages depending on the scenario and size of the input number.

Comments