Factorial Function in JavaScript Using Recursion

Learn how to write a factorial function in JavaScript using recursion, base cases, input validation, and an iterative alternative.

Published

Updated

Read time 3 min read

Reviewed byDeepak Prasad

Factorial Function in JavaScript Using Recursion

A factorial function multiplies a positive integer by every positive integer below it. For example, 5! means 5 * 4 * 3 * 2 * 1, which equals 120. In JavaScript, factorial is a common recursion example because each result can be expressed as a smaller version of the same problem.

The most important part of a recursive factorial function is the base case. Without a base case, the function keeps calling itself until JavaScript throws a maximum call stack error.

Environment: Node.js v20.18.2. After each runnable snippet, the following paragraph states the expected console output (order and values).


Method 1: Write a Recursive Factorial Function

A recursive factorial function calls itself with n - 1 until it reaches 0 or 1.

javascript
function factorial(n) {
  if (n === 0 || n === 1) {
    return 1;
  }

  return n * factorial(n - 1);
}

console.log("factorial-5:", factorial(5));
console.log("factorial-0:", factorial(0));
Output

You should see 2 lines, in order: factorial-5: 120, factorial-0: 1.

The base case returns 1 for 0 and 1. The recursive case multiplies n by the factorial of the previous number.


Method 2: Add Input Validation

A factorial is normally defined for non-negative integers. Add validation so the function fails clearly for negative numbers, decimals, and invalid values.

javascript
function factorial(n) {
  if (!Number.isInteger(n) || n < 0) {
    throw new RangeError("n must be a non-negative integer");
  }

  return n <= 1 ? 1 : n * factorial(n - 1);
}
Output

This version prevents confusing results such as factorial(-1) or factorial(2.5).


Method 3: Use an Iterative Factorial for Large Inputs

Recursion is useful for learning and for naturally recursive data, but an iterative loop avoids deep call stacks.

javascript
function factorialLoop(n) {
  if (!Number.isInteger(n) || n < 0) {
    throw new RangeError("n must be a non-negative integer");
  }

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

console.log(factorialLoop(5));
Output

You should see one line logging 120.

For very large factorials, JavaScript number values can lose precision. Use BigInt if exact integer results matter beyond safe number limits.


Method 4: Factorial with BigInt

Use BigInt when factorial results exceed Number.MAX_SAFE_INTEGER.

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

console.log(factorialBigInt(20n).toString());
Output

You should see one line logging 2432902008176640000.

Do not mix number and BigInt in the same arithmetic expression.


Common Questions About Factorial Recursion in JavaScript

What is the base case for factorial recursion?

The base case is usually n === 0 || n === 1, returning 1.

Why does a recursive factorial cause maximum call stack errors?

It happens when the recursion is too deep or when the function never reaches its base case.

Is recursion required for factorial in JavaScript?

No. Factorial can be written with recursion or a loop. Recursion is useful for learning; a loop is often safer for large inputs.


Summary

A factorial function in JavaScript is a clear example of recursion: define a base case, then solve the larger input by calling the same function with a smaller input. Validate the input before recursion, use an iterative version when call stack depth matters, and use BigInt when the factorial result must stay exact for large numbers.


Official Documentation

Olorunfemi Akinlua

Boasting over five years of experience in JavaScript, specializing in technical content writing and UX design. With a keen focus on programming languages, he crafts compelling content and designs …