Find the factorial of a number in JavaScript
Intermediate · 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. The factorial of 5, written 5!, is 5 × 4 × 3 × 2 × 1 = 120. Factorials count arrangements: 5 people can stand in a line in 120 different orders. They appear in probability, in counting combinations, and in almost every first lesson on loops and recursion.
In this tutorial you will write the factorial three ways: with a loop, with recursion, and with BigInt for numbers too big for ordinary JavaScript numbers. You will also find the exact point where ordinary numbers stop being trustworthy. You need to know what a function and a for loop are.
The rules
n!isn × (n - 1) × ... × 2 × 1.1!is 1.0!is also 1, by definition. There is exactly one way to arrange nothing.- Negative numbers and fractions have no factorial in this sense.
How big factorials get
Factorials grow very fast. 10! is already 3,628,800, and 20! is 2,432,902,008,176,640,000. That speed matters, because JavaScript numbers are only guaranteed exact up to Number.MAX_SAFE_INTEGER:
console.log(Number.MAX_SAFE_INTEGER); // 9007199254740991
Above that, some whole numbers can't be stored and get rounded to a neighbor, with no warning. Step 4 shows what that does to a factorial.
Here is the exercise. Try it yourself first if you like, or follow the steps.
30 Factorial, three ways
fairCompute the factorial of a number. Write it as a loop and as a recursion, and show where ordinary numbers stop being accurate.
Stuck? Three hints, smallest first
- 1.
0!is 1 by definition. Handle it before anything else. - 2. Factorials grow fast:
21!already exceedsNumber.MAX_SAFE_INTEGER. - 3.
BigIntstays exact. Write1nand useBigInt(n)to convert.
Step 1: a loop
Start a running result at 1 and multiply it by every number from 2 up to n:
function factorialLoop(n) {
let out = 1;
for (let i = 2; i <= n; i++) out *= i;
return out;
}
console.log(factorialLoop(5)); // 120
console.log(factorialLoop(1)); // 1
console.log(factorialLoop(0)); // 1
out *= i is short for out = out * i. Starting at 1 handles 0! and 1! for free: the loop doesn't run at all, so the result stays 1. Starting at 0 would make every answer 0.
Step 2: refuse bad input
The loop happily returns 1 for -3 or 2.5, which is nonsense. A function should say so instead of guessing. Number.isInteger checks for a whole number, and throw stops the function with an error:
function factorialLoop(n) {
if (!Number.isInteger(n) || n < 0) throw new RangeError(`factorial needs a whole number 0 or above, got ${n}`);
let out = 1;
for (let i = 2; i <= n; i++) out *= i;
return out;
}
try {
factorialLoop(-1);
} catch (err) {
console.log(err.message); // factorial needs a whole number 0 or above, got -1
}
RangeError is the built-in error type for "this value is outside the allowed range". try and catch let the program catch the error and carry on.
Step 3: recursion
A recursive function calls itself. It works when you can describe a problem in terms of a smaller version of itself, and factorial is exactly that: 5! is 5 × 4!, and 4! is 4 × 3!, and so on. Every recursion also needs a base case, a point where it stops calling itself. Here that is "1 or less gives 1".
function factorialRecursive(n) {
if (n < 0) throw new RangeError('no factorial for negatives');
return n <= 1 ? 1 : n * factorialRecursive(n - 1);
}
console.log(factorialRecursive(5)); // 120
factorialRecursive(5) asks for 5 * factorialRecursive(4), which asks for 4 * factorialRecursive(3), down to factorialRecursive(1), which returns 1. Then the multiplications finish on the way back up: 1, 2, 6, 24, 120. Without the base case it would call itself forever and crash.
Step 4: where ordinary numbers stop being safe
20! is already far above MAX_SAFE_INTEGER, and yet it is stored exactly:
console.log(factorialLoop(20)); // 2432902008176640000
console.log(factorialLoop(21) > Number.MAX_SAFE_INTEGER); // true
Past the safe limit, JavaScript can no longer promise that a whole number is exact. Factorials happen to be easier to store than most big numbers, so 21! and 22! still come out right. 23! doesn't. To check, compare it with an exact BigInt value (Step 5 explains BigInt):
console.log(BigInt(factorialLoop(23)).toString()); // 25852016738884978212864
console.log('25852016738884976640000'); // the true value of 23!
The two differ in the last eight digits, and nothing warned you. That kind of silent error is easy to miss.
Step 5: BigInt stays exact
BigInt is a separate kind of number for whole numbers of any size. You write one with an n on the end, like 1n, and convert an ordinary number with BigInt(n). BigInts can only be mixed with other BigInts, so every value in the loop uses the n form:
function factorialBig(n) {
let out = 1n;
for (let i = 2n; i <= BigInt(n); i++) out *= i;
return out;
}
console.log(factorialBig(21).toString()); // 51090942171709440000
console.log(factorialBig(23).toString()); // 25852016738884976640000
toString() turns the BigInt into ordinary text for printing. Mixing a BigInt with a normal number, like 1n * 2, throws a TypeError, which is why the counter starts at 2n.
The full solution
The complete answer has the loop with its input check, the recursive version, and the BigInt version. It prints a few factorials, compares 21! as a normal number with the BigInt result, and checks that the loop and recursion agree from 0 to 15. One of its lines labels the ordinary-number 21! as "no longer exact". Read that as "no longer safe": as Step 4 showed, its digits still happen to match the BigInt result, but JavaScript no longer guarantees them. Press Run to see the output.
function factorialLoop(n) {
if (!Number.isInteger(n) || n < 0) throw new RangeError(`factorial needs a whole number 0 or above, got ${n}`);
let out = 1;
for (let i = 2; i <= n; i++) out *= i;
return out;
}
function factorialRecursive(n) {
if (n < 0) throw new RangeError('no factorial for negatives');
return n <= 1 ? 1 : n * factorialRecursive(n - 1);
}
// Exact for any size, because BigInt does not lose precision.
function factorialBig(n) {
let out = 1n;
for (let i = 2n; i <= BigInt(n); i++) out *= i;
return out;
}
console.log('5! =', factorialLoop(5));
console.log('0! =', factorialLoop(0));
console.log('20! =', factorialLoop(20), '(still exact)');
console.log('21! =', factorialLoop(21), '(no longer exact)');
console.log('21! =', factorialBig(21).toString(), '(BigInt, exact)');
console.log('is 21! safe as a Number?', factorialLoop(21) <= Number.MAX_SAFE_INTEGER);
Output
8 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 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('5 factorial', factorialLoop(5), 120);
test('0 factorial is 1', factorialLoop(0), 1);
test('1 factorial is 1', factorialLoop(1), 1);
test('recursion agrees up to 15', Array.from({ length: 16 }, (_, i) => i).every((n) => factorialLoop(n) === factorialRecursive(n)), true);
test('20 factorial is still exact', factorialLoop(20), 2432902008176640000);
test('21 factorial exceeds safe integers', factorialLoop(21) > Number.MAX_SAFE_INTEGER, true);
test('BigInt keeps it exact', factorialBig(21).toString(), '51090942171709440000');
test('negatives are refused', (() => { try { factorialLoop(-1); return false; } catch { return true; } })(), true);
20! is the last factorial an ordinary JavaScript number holds exactly. From 21! upward the result looks fine and is wrong in its low digits, with no warning at all — which is exactly the kind of failure that survives into production. BigInt is the fix, and the n suffix on literals is how you write one.
Common mistakes
- Starting the result at 0. Every product comes out 0. Factorials start at 1.
- No base case in the recursion. The function calls itself forever, and JavaScript stops it with
RangeError: Maximum call stack size exceeded. - Trusting large results. Above
Number.MAX_SAFE_INTEGER, results can be wrong in the last digits with no warning. UseBigIntfor big factorials.
Try it yourself
- Find the first
nwherefactorialLoop(n)no longer matchesfactorialBig(n), using a loop andBigInt(factorialLoop(n)) === factorialBig(n). - Count how many digits
100!has, usingfactorialBig(100).toString().length. - Write
choose(n, k), the number of ways to pickkitems fromn:n! / (k! × (n - k)!). Check thatchoose(5, 2)is 10.