How to write the factorial function with reduce and range in JavaScript?

In this tutorial, we'll learn how to calculate factorials using JavaScript's reduce() method combined with array generation techniques. This approach demonstrates functional programming concepts while solving a common mathematical problem.

Understanding reduce() and range Functions

The reduce() function processes an array and reduces it to a single value by applying a function to each element. It takes an accumulator (which stores the result) and the current array value as parameters.

const nums = [1, 2, 3, 4, 5];
const sum = nums.reduce((acc, val) => acc + val, 0);
console.log(sum);
15

For range generation, JavaScript doesn't have a built-in range function, but we can create arrays using Array.from():

const range = (start, end, step = 1) => Array.from({ length: Math.floor((end - start) / step) + 1 }, (_, i) => start + (i * step));
const numbers = range(1, 5, 1);
console.log(numbers);
[1, 2, 3, 4, 5]

What is Factorial?

Factorial of a non-negative integer n is the product of all positive integers less than or equal to n. For example, factorial of 4 is 4 × 3 × 2 × 1 = 24.

Implementation Using Array.from() and reduce()

Here's how to implement factorial using array generation and reduce:

function factorial(num) {
    if (num < 0) return undefined; // Factorial undefined for negative numbers
    if (num === 0 || num === 1) return 1;
    
    return Array.from({length: num}, (_, i) => i + 1)
           .reduce((acc, val) => acc * val, 1);
}

console.log("Factorial of 5:", factorial(5));
console.log("Factorial of 10:", factorial(10));
console.log("Factorial of 0:", factorial(0));
console.log("Factorial of 1:", factorial(1));
Factorial of 5: 120
Factorial of 10: 3628800
Factorial of 0: 1
Factorial of 1: 1

How It Works

The implementation works in two steps:

  1. Array.from({length: num}, (_, i) => i + 1) creates an array [1, 2, 3, ..., num]
  2. reduce((acc, val) => acc * val, 1) multiplies all values together, starting with initial value 1
// Let's trace through factorial(4)
const num = 4;
const numbersArray = Array.from({length: num}, (_, i) => i + 1);
console.log("Generated array:", numbersArray);

const result = numbersArray.reduce((acc, val) => {
    console.log(`acc: ${acc}, val: ${val}, result: ${acc * val}`);
    return acc * val;
}, 1);

console.log("Final result:", result);
Generated array: [1, 2, 3, 4]
acc: 1, val: 1, result: 1
acc: 1, val: 2, result: 2
acc: 2, val: 3, result: 6
acc: 6, val: 4, result: 24
Final result: 24

Alternative: Using Custom Range Function

function range(start, end) {
    return Array.from({length: end - start + 1}, (_, i) => start + i);
}

function factorialWithRange(num) {
    if (num < 0) return undefined;
    if (num === 0 || num === 1) return 1;
    
    return range(1, num).reduce((acc, val) => acc * val, 1);
}

console.log("Using range function:", factorialWithRange(6));
Using range function: 720

Complexity Analysis

Aspect Complexity Explanation
Time O(n) Creates array of n elements, then processes each once
Space O(n) Stores array of n elements before reduction

Conclusion

Using reduce() with array generation provides a functional programming approach to calculate factorials. While not the most memory-efficient method, it demonstrates powerful array manipulation techniques in JavaScript.

Updated on: 2026-03-15T23:19:00+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements