Emmanuel Akinfulubi

JavaScriptMath

Factorial with a loop vs recursion in JavaScript

Advanced · 4 min read

The factorial of a number, written n!, is every whole number from 1 up to n multiplied together. 5! is 5 * 4 * 3 * 2 * 1 = 120. Factorials count arrangements: 5 books can be put on a shelf in 120 different orders. They show up in probability, in combinations and in almost every first lesson on loops and recursion.

In this tutorial you will write factorial twice, once with a loop and once with recursion, and then push it until it breaks. A JavaScript number gives out in three different places, and you will find all three. Then you will write a BigInt version that never breaks. You need to know for loops and arrow functions.

Recursion in one paragraph

A recursive function is one that calls itself on a smaller version of the same problem. Factorials fit this well, because 5! is just 5 * 4!. You need a base case, a point where the function stops calling itself, or it would go on forever. For factorials, the base case is "1! is 1".

Three limits

JavaScript numbers can only hold so much. As factorials grow, you'll pass three lines:

  1. Safe: below Number.MAX_SAFE_INTEGER (about 9 quadrillion), every whole number is stored exactly.
  2. Exact: some bigger numbers can still be stored exactly, if they end in enough binary zeros.
  3. Finite: past about 1.8e308, everything becomes Infinity.

Here is the exercise. Have a go on your own first if you like, then read on and we will build it together.

89 Factorials, and the three places a double gives out

hard

Write factorial with a loop and again with recursion, then find the last factorial below Number.MAX_SAFE_INTEGER, the last one that is still exactly representable as a double, and the last one that is finite at all. Then write the BigInt version and read 25! back in full.

Stuck? Three hints, smallest first
  1. 1. Two different limits: past MAX_SAFE_INTEGER a value can still be exact if its trailing bits are zero.
  2. 2. A factorial has a lot of factors of 2, which is why exactness survives further than safety does.
  3. 3. BigInt(x) === bigVersion(n) is how you ask whether the double was exact.

Step 1: the loop version

Step 1

const factorial = (n) => {
  let result = 1;
  for (let i = 2; i <= n; i++) result *= i;
  return result;
};
console.log(factorial(5), factorial(10)); // 120 3628800
console.log(factorial(0), factorial(1));  // 1 1

Start at 1 and multiply by every number from 2 up to n. For 0 and 1 the loop never runs, so the answer is 1, which is correct: 0! is defined as 1.

Step 2: the recursive version

Step 2

const factorialRec = (n) => (n <= 1 ? 1 : n * factorialRec(n - 1));
console.log(factorialRec(10));                   // 3628800
console.log(factorialRec(20) === factorial(20)); // true

n <= 1 ? 1 : ... is the base case. Every other call multiplies n by the factorial of n - 1. Both versions do the same multiplications, so they give the same answers.

Step 3: the first limit, safe

Step 3

console.log(factorial(18));                         // 6402373705728000
console.log(Number.isSafeInteger(factorial(18)));   // true
console.log(Number.isSafeInteger(factorial(19)));   // false

18! is the last factorial below Number.MAX_SAFE_INTEGER. 19! is already past it.

Step 4: unsafe, but still exact

Past the safe line is not the same as wrong. To check whether a number is exactly right, compare it with a BigInt version. BigInt is a number type for whole numbers of any size, written with an n at the end.

Step 4

const factorialBig = (n) => {
  let result = 1n;
  for (let i = 2n; i <= BigInt(n); i++) result *= i;
  return result;
};
const exactAt = (n) => BigInt(factorial(n)) === factorialBig(n);
console.log([19, 20, 21, 22, 23].map(exactAt)); // [ true, true, true, true, false ]

19! to 22! are still exact. A factorial contains many factors of 2, so in binary it ends in a long row of zeros, and a double can store those for free. "Unsafe" only means some whole numbers nearby can't be stored. This one can.

Step 5: the second limit, exact

At 23! the answer goes wrong.

Step 5

console.log(String(BigInt(factorial(23)))); // 25852016738884978212864
console.log(String(factorialBig(23)));      // 25852016738884976640000

The two agree for 16 digits, then differ. There is no error or warning: you get a confident, wrong answer.

Step 6: the third limit, finite

Step 6

console.log(factorial(170));               // 7.257415615307994e+306
console.log(factorial(171) === Infinity);  // true

170! is the largest factorial a double can hold at all. 171! overflows to Infinity.

Step 7: BigInt all the way

Step 7

console.log(String(factorialBig(25))); // 15511210043330985984000000

All 26 digits of 25!, exactly. The BigInt loop has no ceiling, only memory and time.

Step 8: the missing guard

Try some inputs that have no factorial:

Step 8

console.log(factorial(-3), factorial(2.5)); // 1 2

For -3, the loop never runs and returns 1. For 2.5, it runs once (i = 2) and returns 2. Both answers look fine and are nonsense. Add a check:

JavaScript

const factorialGuarded = (n) => (Number.isInteger(n) && n >= 0 ? factorial(n) : NaN);
console.log(factorialGuarded(-3), factorialGuarded(2.5), factorialGuarded(5)); // NaN NaN 120

NaN says clearly "this has no answer".

The full solution

The answer panel has the loop, recursive, BigInt and guarded versions plus exactAt, and prints all three limits, 25! in full, the unguarded edges and 20! / 18!. Press Run to see the output.

The answer

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

const factorialRec = (n) => (n <= 1 ? 1 : n * factorialRec(n - 1));

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

// The empty loop returns 1 for any n below 2, including nonsense. Say so.
const factorialGuarded = (n) => (Number.isInteger(n) && n >= 0 ? factorial(n) : NaN);

const exactAt = (n) => BigInt(factorial(n)) === factorialBig(n);

console.log('18!, 19!        :', factorial(18), factorial(19));
console.log('safe?           :', Number.isSafeInteger(factorial(18)), Number.isSafeInteger(factorial(19)));
console.log('exact 19 to 23  :', [19, 20, 21, 22, 23].map(exactAt));
console.log('23! as a double :', String(BigInt(factorial(23))));
console.log('23! really      :', String(factorialBig(23)));
console.log('170!, 171!      :', factorial(170), factorial(171));
console.log('25! in BigInt   :', String(factorialBig(25)));
console.log('unguarded edges :', factorial(-3), factorial(2.5));
console.log('20! / 18!       :', factorial(20) / factorial(18));

Output


      
9 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 9 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

9 checks

test('18! is the last factorial below MAX_SAFE_INTEGER; 19! is already past it', [factorial(18), Number.isSafeInteger(factorial(18)), Number.isSafeInteger(factorial(19))], [6402373705728000, true, false]);
test('19! through 22! are unsafe but still exactly representable', [19, 20, 21, 22].map(exactAt), [true, true, true, true]);
test('23! is the first factorial a double gets wrong', [exactAt(23), String(BigInt(factorial(23))), String(factorialBig(23))], [false, '25852016738884978212864', '25852016738884976640000']);
test('170! is the largest finite one, and 171! is Infinity', [factorial(170), factorial(171) === Infinity], [7.257415615307994e+306, true]);
test('the BigInt version keeps all 26 digits of 25!', String(factorialBig(25)), '15511210043330985984000000');
test('0! and 1! are both 1, which the empty loop gives you for nothing', [factorial(0), factorial(1), String(factorialBig(0))], [1, 1, '1']);
test('but the empty loop also answers -3 and 2.5, so a guard is not optional', [factorial(-3), factorial(2.5), Number.isNaN(factorialGuarded(-3)), Number.isNaN(factorialGuarded(2.5))], [1, 2, true, true]);
test('the recursive version agrees exactly, including where the double is unsafe', [factorialRec(10), factorialRec(20) === factorial(20)], [3628800, true]);
test('and 20! divided by 18! is 380, which is 19 times 20, to the last bit', [factorial(20) / factorial(18), factorial(20) / factorial(18) === 19 * 20], [380, true]);

There are three separate ceilings here and they are usually confused with each other. 18! is the last factorial below Number.MAX_SAFE_INTEGER. 22! is the last one that is still exactly representable as a double — a factorial has a great many factors of 2, so its low bits are already zero and the format has room for them even past the safe range. 170! is the last one that is finite; 171! overflows to Infinity. Between 19! and 22! a double is unsafe and exact at the same time, which is not a contradiction: unsafe means some integer near it is unrepresentable, not that this one is wrong.

23! is where the arithmetic actually breaks, and it breaks quietly. The double reads 25852016738884978212864 against a true value of 25852016738884976640000, so the answer is wrong from the 17th digit with no flag raised anywhere. If a factorial is going anywhere near 20, use BigInt.

The guard is the other lesson. for (let i = 2; i <= n; i++) simply never runs for n = -3, so the function returns 1 — a confident, wrong, positive answer. For 2.5 it runs once and returns 2. Neither input is a factorial, and the loop has no way to say so; only an explicit check does.

Common mistakes

  • Treating "unsafe" as "wrong". 19! to 22! are unsafe but exact. 23! is the first wrong one.
  • Trusting a large factorial as a Number. From 23! onward the digits are wrong without any error. Use BigInt.
  • Skipping the input check. The loop returns 1 for -3 and 2 for 2.5. Reject anything that isn't a whole number 0 or above.

Try it yourself

  1. Work out factorial(20) / factorial(18) and explain why it is 380.
  2. Write factorialBigGuarded(n) that throws an error for negative input instead of returning 1n.
  3. How many digits does 100! have? Use factorialBig and String(...).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.