JS CodeLab
algorithmsintermediate

JavaScript Factorial Algorithm (Recursive Solution)

•
Updated

Direct Answer & Overview

The factorial of a non-negative integer n is the product of all positive integers less than or equal to n, denoted as n!. In JavaScript, factorials are calculated using recursive functions with defined base cases or iterative accumulator loops.

#algorithms#recursion#math#factorials

JavaScript Source Code

example.js
function factorial(number) {
  if (number <= 1) {
    return 1;
  }

  return number * factorial(number - 1);
}

console.log(factorial(5));

How does this JavaScript code work?

Factorial (n!) is mathematically defined as n * (n - 1) * ... * 1, with 0! = 1. In recursive programming, a function calls itself with smaller inputs until reaching a termination condition known as the base case (`number <= 1`). Each recursive call pushes an execution frame onto the JavaScript call stack. When the base case returns 1, the frames unwind and compute the final multiplied integer.

What is the expected terminal output?

Executing this code in JS CodeLab produces the following stdout sequence in the developer console:

Console Standard Output
120

Common mistakes to avoid

  • !Forgetting the base case (number <= 1), triggering RangeError: Maximum call stack size exceeded.
  • !Not handling negative numbers, which mathematically do not have integer factorials and cause infinite recursion.
  • !Calling factorial on large numbers (n > 170) which exceed JavaScript's Number.MAX_VALUE and evaluate to Infinity.
  • !Preferring recursion over iteration for huge numbers where memory constraints or tail call optimization limitations apply.

Frequently Asked Questions

What happens if a recursive function does not have a base case?

The function calls itself indefinitely until the JavaScript engine exhausts call stack memory, throwing a RangeError: Maximum call stack size exceeded.

How can you compute factorials of very large integers in JavaScript?

Use BigInt (e.g. 100n) to prevent 64-bit float precision loss and avoid premature overflow into Infinity.

Is an iterative loop faster than recursion for factorials?

Yes. An iterative for-loop runs in O(n) time and O(1) auxiliary space, avoiding the call stack overhead and function frame allocations of recursion.