Emmanuel Akinfulubi

JavaScriptRecursion

Factorial using recursion in JavaScript

Beginner · 4 min read

The factorial of a number is what you get when you multiply it by every whole number below it, down to 1. Mathematicians write it with an exclamation mark: 5! means 5 × 4 × 3 × 2 × 1, which is 120. Factorials count arrangements. If five friends line up for a photo, there are 5! different orders they can stand in.

In this tutorial you will write factorial(n) as a recursive function, one that calls itself. Then you will find the exact point where JavaScript's numbers stop giving the right answer, and fix it with BigInt. You need to know what a function and an if statement are. Recursion is explained from zero.

Recursion in plain words

A recursive function solves a big problem by doing one small piece of work and handing the rest to itself. Factorials fit this perfectly, because each one contains the one below it:

Worked example

5! = 5 × 4 × 3 × 2 × 1
   = 5 × (4 × 3 × 2 × 1)
   = 5 × 4!

So factorial(5) can be "5 times factorial(4)". That is the recursive case. But the function can't call itself forever. It needs a base case: an input small enough to answer straight away, without another call. For factorials, 1! is 1, and by definition 0! is also 1.

Every recursive function you write has these two parts. Get the base case wrong and the calls never stop.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

1 Factorial of a number

easy

Multiply every whole number from 1 up to n. So 5! is 5 × 4 × 3 × 2 × 1, which is 120. Then find where the answer stops being trustworthy.

Stuck? Three hints, smallest first
  1. 1. The base case is n <= 1 returning 1, not n === 1, because 0! is also 1.
  2. 2. A negative input has no factorial. Refuse it rather than recursing forever.
  3. 3. Factorials outgrow Number fast. BigInt is the fix, and it needs the n suffix on literals.

Step 1: write the base case first

Start with the answer you already know: small inputs return 1.

Step 1

function factorial(n) {
  if (n <= 1) return 1;
  return 'not done yet';
}
console.log(factorial(0)); // 1
console.log(factorial(1)); // 1

Notice the check is n <= 1, not n === 1. That one character matters, as the next step shows.

Step 2: add the recursive case

Now hand the rest of the work to a smaller call:

Step 2

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
console.log(factorial(5));  // 120
console.log(factorial(10)); // 3628800

Here is what happens inside factorial(3). Each call waits for the one below it, and the answers come back up the chain:

Worked example

factorial(3) = 3 * factorial(2)
             = 3 * (2 * factorial(1))
             = 3 * (2 * 1)
             = 6

Now the wrong turn. If the base case were n === 1, then factorial(0) would call factorial(-1), then factorial(-2), and never reach 1. JavaScript gives up and throws RangeError: Maximum call stack size exceeded. The call stack is the list of calls still waiting for an answer, and it has a size limit.

Step 3: refuse bad input

Negative numbers and decimals have no factorial in this sense. A negative number would also slip straight into the base case and wrongly return 1. So refuse them before doing anything else:

Step 3

function factorial(n) {
  if (!Number.isInteger(n) || n < 0) throw new RangeError('factorial needs a whole number 0 or above');
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
try {
  factorial(-1);
} catch (e) {
  console.log(e.constructor.name); // 'RangeError'
}

Number.isInteger is true only for whole numbers, so 2.5 is refused too.

Step 4: compare it with a loop

Recursion is one way to describe the problem. A loop is another, and it gives the same answers without stacking up calls:

Step 4

function factorialLoop(n) {
  let total = 1;
  for (let i = 2; i <= n; i++) total *= i;
  return total;
}
console.log(factorialLoop(5)); // 120
console.log(factorialLoop(0)); // 1

For 0 the loop never runs, so total stays at 1, which is the right answer.

Step 5: find where the numbers break

Factorials grow very fast. A JavaScript Number can only hold whole numbers exactly up to Number.MAX_SAFE_INTEGER, which is 2^53 - 1 (about 9 quadrillion). Number.isSafeInteger tells you whether a value is still in that safe range:

Step 5

function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}
console.log(Number.isSafeInteger(factorial(18))); // true
console.log(Number.isSafeInteger(factorial(19))); // false
console.log(factorial(20) + 1 === factorial(20)); // true

18! is the last safe one. Past it, adding 1 can change nothing at all, which is what the last line shows. A few more values are still stored exactly by luck, but 23! is the first one a Number simply gets wrong.

Step 6: use BigInt for exact answers

BigInt is a second kind of number in JavaScript that holds whole numbers of any size exactly. You write one by putting n after the digits, like 23n, and you can only do math between two BigInts:

Step 6

function factorialBig(n) {
  return n <= 1n ? 1n : n * factorialBig(n - 1n);
}
console.log(factorialBig(23n).toString()); // '25852016738884976640000'

It is the same recursion, with every number written as a BigInt.

The full solution

The panel has the checked recursive version, the loop, the BigInt version, and checks that pin down exactly where Number breaks. Press Run to see the output.

The answer

function factorial(n) {
  if (!Number.isInteger(n) || n < 0) throw new RangeError('factorial needs a whole number 0 or above');
  if (n <= 1) return 1;               // covers 0! and 1!, both of which are 1
  return n * factorial(n - 1);
}

// The loop version. Same answers, no stack frames.
function factorialLoop(n) {
  let total = 1;
  for (let i = 2; i <= n; i++) total *= i;
  return total;
}

// Exact for any size, because BigInt does not round.
function factorialBig(n) {
  return n <= 1n ? 1n : n * factorialBig(n - 1n);
}

const refused = (() => { try { factorial(-1); return 'no error'; } catch (e) { return e.constructor.name; } })();

console.log('0! =', factorial(0), ' 5! =', factorial(5), ' 10! =', factorial(10));
console.log('18! =', factorial(18), '<- still a safe integer');
console.log('19! =', factorial(19), '<- past 2^53, so ±1 stops meaning anything');
console.log('20! + 1 === 20! ?', factorial(20) + 1 === factorial(20));
console.log('23! as a Number:', factorial(23));
console.log('23! as a BigInt:', factorialBig(23n).toString(), '<- the true answer');
console.log('negative input  :', refused);

Output


      
12 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 12 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

12 checks

test('0! is 1', factorial(0), 1);
test('1! is 1', factorial(1), 1);
test('5! is 120', factorial(5), 120);
test('10! is 3628800', factorial(10), 3628800);
test('the loop agrees for 0 to 15', Array.from({ length: 16 }, (_, i) => factorial(i) === factorialLoop(i)).every(Boolean), true);
test('a negative input is refused', refused, 'RangeError');
test('18! is the last safe integer factorial', Number.isSafeInteger(factorial(18)), true);
test('19! is already unsafe', Number.isSafeInteger(factorial(19)), false);
test('so adding 1 to 20! changes nothing', factorial(20) + 1 === factorial(20), true);
test('22! is still exactly representable', BigInt(factorial(22)) === factorialBig(22n), true);
test('23! is the first one that is simply wrong', BigInt(factorial(23)) === factorialBig(23n), false);
test('BigInt gets 23! right', factorialBig(23n).toString(), '25852016738884976640000');

Two different limits are at work, and mixing them up is common. Number.MAX_SAFE_INTEGER is 2^53 - 1, and 18! is the last factorial below it — past that, + 1 silently does nothing. But exact representability reaches further: a factorial has many factors of 2, so it ends in many binary zeros, and 22! is still stored exactly. 23! is the first factorial a Number gets wrong. Neither number is guessable; both assertions above check it.

Common mistakes

  • Using n === 1 as the base case. factorial(0) then never stops and throws a RangeError. Use n <= 1.
  • Trusting big results. factorial(25) returns a number without complaint, but it isn't the true answer. Use BigInt past 18!.
  • Mixing BigInt and Number. 5n * 4 throws a TypeError. Write every number in the BigInt version with the n suffix.

Try it yourself

  1. Write sumTo(n) that adds 1 + 2 + ... + n recursively. What should the base case be?
  2. Count how many times factorial is called for factorial(6). Add a counter variable outside the function and increase it on each call.
  3. Use factorialBig to find how many digits 50! has. (Hint: .toString().length.)

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.