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.