How to calculate the factorial of a number in JavaScript
Calculating factorials is important for mathematical computations, combinatorics, probability calculations, and implementing features like permutation generators or statistical analysis in JavaScript applications. With over 25 years of experience in software development and as the creator of CoreUI, I’ve implemented factorial calculations in components like mathematical utilities, educational tools, and data analysis features where precise mathematical operations are essential for accurate results. From my extensive expertise, the most straightforward approach for small numbers is using recursion, while iteration provides better performance and avoids stack overflow for larger numbers. Both methods have their place depending on the use case and performance requirements.
Use recursion or iteration to calculate the factorial of a number.
// Recursive approach
const factorialRecursive = (n) => {
if (n <= 1) return 1
return n * factorialRecursive(n - 1)
}
// Iterative approach
const factorialIterative = (n) => {
let result = 1
for (let i = 2; i <= n; i++) {
result *= i
}
return result
}
// Usage: factorialRecursive(5) or factorialIterative(5) returns 120
The recursive approach defines factorial mathematically: n! = n × (n-1)!, with the base case that 0! and 1! equal 1. The function calls itself with decreasing values until reaching the base case. The iterative approach uses a loop to multiply consecutive numbers from 2 to n. Both methods produce the same result: factorial(5) = 5 × 4 × 3 × 2 × 1 = 120. The recursive version is more intuitive and matches the mathematical definition, while the iterative version is more efficient for larger numbers and avoids potential stack overflow issues.
Best Practice Note:
This is the same approach we use in CoreUI components for mathematical calculations, educational demonstrations, and statistical computations across our component library.
For very large numbers, consider using BigInt: BigInt(result) * BigInt(i)
to handle values beyond JavaScript’s number precision limit. The iterative approach is generally preferred for production code due to better performance and stack safety. Always validate input to ensure non-negative integers.