The factorial of a number N (written N!) is the product of every whole number from 1 up to N — for example, 5! = 5 × 4 × 3 × 2 × 1 = 120. It's a small problem, but it's the standard first example for comparing an iterative solution (using a loop) against a recursive one, where a function calls itself.

Factorial Using a Loop (Iterative)

function factorialIterative(n) {
  let result = 1;
  for (let i = 2; i <= n; i++) {
    result *= i;
  }
  return result;
}

console.log(factorialIterative(5));

Output:

120

This version keeps a running result and multiplies it by every integer from 2 to n. It's straightforward, uses a fixed and small amount of memory no matter how large n is, and is generally the better choice for production code.


Factorial Using Recursion

A recursive function solves a problem by calling itself on a smaller version of the same problem, until it reaches a case simple enough to answer directly — the base case. For factorial, the base case is 0! = 1 and 1! = 1, and every other case is defined as n! = n × (n - 1)!.

function factorialRecursive(n) {
  // Base case: stop the recursion
  if (n <= 1) {
    return 1;
  }
  // Recursive case: n! = n * (n - 1)!
  return n * factorialRecursive(n - 1);
}

console.log(factorialRecursive(5));

Output:

120

Tracing it through: factorialRecursive(5) calls 5 * factorialRecursive(4), which calls 4 * factorialRecursive(3), and so on down to factorialRecursive(1), which returns 1 without calling itself again. The calls then "unwind" back up, multiplying as they go: 1 → 2 → 6 → 24 → 120.

Every recursive function needs a base case like this one — without it, the function would keep calling itself forever and eventually crash with a "Maximum call stack size exceeded" error.