Factorial Program in JavaScript


In this short article, I show you how to write a program to find factorial of any number using JavaScript.

Factorial Program in JavaScript

In the below program, we created two functions to find factorial of any number using JavaScript.
  • factorialIterative()
  • factorial()
function factorialIterative(number) {
    if (number < 0) {
        return undefined;
    }
    let total = 1;
    for (let n = number; n > 1; n--) {
        total *= n;
    }
    return total;
}

function factorial(n) {
    if (n < 0) {
        return undefined;
    }
    if (n === 1 || n === 0) {
        return 1;
    }
    return n * factorial(n - 1);
}

let value = factorial(5);
let value1 = factorialIterative(5);

console.log("factorial of 5 -> " + value);
console.log("factorial Iterative of 5 -> " + value1);

Output

factorial of 5 -> 120
factorial Iterative of 5 -> 120

Demo

For the best learning experience, I highly recommended that you open a console (which, in Chrome and Firefox, can be done by pressing Ctrl+Shift+I), navigate to the "console" tab, copy-and-paste each JavaScript code example from this guide, and run it by pressing the Enter/Return key.


Comments