Factorial in JavaScript

๐Ÿงฎ Factorial in JavaScript โ€“ A Detailed Explanation with Examples

If you’re learning JavaScript or preparing for coding interviews, understanding factorial and how to implement it in JavaScript is essential. In this blog post, weโ€™ll break down what a factorial is, how to write factorial functions using different methods, and which approach is best for real-life use.


โœ… What is a Factorial?

In mathematics, the factorial of a non-negative integer n is the product of all positive integers less than or equal to n.

It’s denoted by n!.
For example:

5! = 5 ร— 4 ร— 3 ร— 2 ร— 1 = 120

By definition:

  • 0! is 1
  • Factorial is not defined for negative numbers

๐Ÿ’ก Real-World Use Cases of Factorial

Factorial is commonly used in:

  • Combinatorics (e.g., permutations and combinations)
  • Mathematics and Statistics
  • Computer Science Algorithms (like recursion and dynamic programming)

๐Ÿง‘โ€๐Ÿ’ป Factorial in JavaScript โ€“ Different Approaches

Letโ€™s explore three popular ways to calculate the factorial in JavaScript:


1. ๐Ÿ” Iterative Approach

function factorialIterative(n) {
  if (n < 0) return "Factorial not defined for negative numbers";
  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
}

console.log(factorialIterative(5)); // 120

โœ… Pros:

  • Simple and efficient
  • Avoids stack overflow

โŒ Cons:

  • Slightly more verbose than recursion

2. ๐Ÿ” Using Recursion

function factorialRecursive(n) {
  if (n < 0) return "Factorial not defined for negative numbers";
  if (n === 0 || n === 1) return 1;
  return n * factorialRecursive(n - 1);
}

console.log(factorialRecursive(5)); // 120

โœ… Pros:

  • Clean and elegant
  • Great for understanding recursion

โŒ Cons:

  • Can lead to stack overflow for large n

3. โšก One-Liner Using Array.reduce()

const factorialOneLiner = n =>
  n < 0 ? "Factorial not defined" :
  n === 0 ? 1 :
  [...Array(n)].map((_, i) => i + 1).reduce((a, b) => a * b);

console.log(factorialOneLiner(5)); // 120

โœ… Pros:

  • Stylish and modern

โŒ Cons:

  • Less readable for beginners
  • Less performant than other methods

โš–๏ธ Which Approach Should You Use?

ApproachBest ForAvoid When
IterativePerformance, reliabilityNever โ€“ it’s always safe
RecursiveLearning, small valuesLarge numbers (n > 10,000)
One-liner (ES6+)Fancy syntax, short scriptsProduction use, big inputs

โœ… Recommendation:
Use the iterative approach for most real-world applications due to its safety and speed.


๐Ÿงช Bonus: Factorial with Memoization

If you’re calculating factorials repeatedly, use memoization to cache results:

const memo = {};

function factorialMemo(n) {
  if (n < 0) return "Not defined";
  if (n === 0 || n === 1) return 1;
  if (memo[n]) return memo[n];
  return memo[n] = n * factorialMemo(n - 1);
}

๐Ÿ“ Conclusion

Understanding how to implement factorial in JavaScript helps you master the concepts of loops, recursion, and performance. Practice all three approaches and decide based on the context of your application.