Definition
n! & 0!
Product 1…n; empty product gives 0! = 1.
Factorial n! is the product of integers from 1 through n, with 0! = 1. This tutorial covers recursive and iterative solutions, BigInt factorial, a live preview, worked JavaScript examples, edge cases, and complexity.
n! & 0!
Product 1…n; empty product gives 0! = 1.
n·(n-1)!
Classic recursive interview form.
O(1) space
Loop multiply avoids recursion-depth limits.
BigInt
Exact large factorials beyond the Number safe range.
n ≤ 20
Exact factorials in the browser for small n.
Multiplies
Both styles use Θ(n) multiplications.
Factorial for an integer n ≥ 0 is the product of every integer from 1 through n. By definition, 0! = 1 (the empty product). Example: 5! = 5 × 4 × 3 × 2 × 1 = 120.
Factorials count permutations: n! is the number of ways to order n distinct objects. Values grow extremely fast — a correct small-n program is easy; a robust one also validates n ≥ 0 and prefers loops for large n.
It is the classic interview problem for base cases, recurrence vs loops, and recursion-depth tradeoffs.
Empty product — say it clearly in interviews.
n! = n · (n-1)! for n ≥ 1.
Iteration avoids recursion-depth errors.
Reject n < 0 — factorial is undefined there.
In short: for n ≥ 0, multiply 1 through n (or return 1 when n is 0 or 1).
Given a nonnegative integer n, compute n!.
# 0! = 1
# 5! = 5 * 4 * 3 * 2 * 1 = 120
# 6! = 6 * 5! = 720 | Item | Type | Description |
|---|---|---|
n | number | Nonnegative integer (reject negatives). |
| Return / print | number / text | Exact value of n!. |
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
} | Method | Idea | Notes |
|---|---|---|
| Recursive | n * factorial(n-1) | Matches theory; O(n) stack |
| Iterative | Multiply 2…n in a loop | O(1) extra space |
BigInt factorial | BigInt loop | Best for production code |
| Goal | Pattern |
|---|---|
| Base case | if n <= 1: return 1 |
| Recurrence | return n * factorial(n - 1) |
| Loop | for (let i = 2; i <= n; i++) result *= i |
| BigInt loop | BigInt factorial(n) |
| Classic values | 0! = 1, 5! = 120, 10! = 3628800 |
| Reject | n < 0 → raise / error |
Three ways to compute n! — pick by clarity and constraints.
n * f(n-1)Teaches base case + recurrence
loop *= iSafer for large n (no stack depth)
BigInt factorialOptimized and battle-tested
both + tradeoffShow recursion, then mention loop
Reach for factorial when products, permutations, or recursion drills appear.
First recursion problem many candidates see.
Permutations and combinations use n!.
Clear base case and single recursive call.
Natural precursor to recursive sequences.
Validate n ≥ 0 before computing.
Key benefit: one short function that forces clear thinking about base cases, space, and growth.
Exact factorial for 0 ≤ n ≤ 20 (safe to display exactly in JavaScript).
Three complete JavaScript programs with Try it Yourself editors — recursive, iterative, and BigInt exact factorial. Click View Output to reveal sample console results.
Base case + recurrence for interview explanations.
Classic recursive style with input validation.
function factorialRecursive(n) {
if (n < 0) {
throw new Error("Factorial is not defined for negative integers.");
}
if (n <= 1) {
return 1;
}
return n * factorialRecursive(n - 1);
}
const number = 5;
const result = factorialRecursive(number);
console.log(`Factorial of ${number} is: ${result}`); Each call reduces n until the base case 1, then products are built while returning. Stack depth is O(n), so large n can raise stack overflow.
Same numeric result with O(1) auxiliary space.
No recursion-depth risk; multiply factors from 2 to n.
function factorialIterative(n) {
if (n < 0) {
throw new Error("Factorial is not defined for negative integers.");
}
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
const number = 5;
console.log(`Factorial of ${number} is: ${factorialIterative(number)}`); The loop multiplies 1 by every integer from 2 to n. For n in {0, 1}, the loop body does not run and result stays 1.
Exact integers when Number is no longer safe.
BigIntCompute exact large factorials beyond the Number safe range.
function factorialBigInt(n) {
if (n < 0) {
throw new Error("Factorial is not defined for negative integers.");
}
let result = 1n;
for (let i = 2n; i <= BigInt(n); i++) {
result *= i;
}
return result;
}
for (const n of [0, 1, 5, 10, 20]) {
console.log(`${n}! = ${factorialBigInt(n)}`);
} Prefer BigInt when exact large factorials are required. In interviews, write recursive or iterative yourself first, then mention BigInt for production-scale exact values.
Reject n < 0; factorial is not defined for negatives.
If n ≤ 1, return 1 (covers 0! and 1!).
Compute n * factorial(n-1), or multiply 2…n.
Exact product for nonnegative n.
n = 5Trace the recursive expansion for the classic interview value.
| Call | Expression | Returns |
|---|---|---|
f(5) | 5 * f(4) | waits |
f(4) | 4 * f(3) | waits |
f(3) | 3 * f(2) | waits |
f(2) | 2 * f(1) | waits |
f(1) | base | 1 |
| unwind | 2*1 … 5*24 | 120 |
Final answer: 5! = 120.
Where factorial shows up beyond the interview prompt.
Base case, recurrence, and loop tradeoffs.
Example: write factorial(n).
n! counts orderings of n items.
Example: 5 books → 120 orders.
C(n, k) uses factorials in the formula.
Example: n! / (k!(n-k)!).
Single recursive call with a clear stop.
Example: chalkboard unwind of 5!.
Warm-up for recursive series problems.
Example: next page in this chain.
Stirling’s approximation for large-n intuition.
Example: estimate digit growth of n!.
Pro Tip: say “0! = 1” before coding — interviewers listen for that base case.
Why this pattern works well in interviews and classwork.
One recurrence and one base case tell the whole story.
Recursion matches theory; loops scale better.
0, 1, 5, and 20 are easy to verify.
BigInt factorial is ready for production use.
Pro Tip: show recursion for the whiteboard, then say you would ship the iterative or BigInt version.
Small habits that keep factorial solutions interview-ready.
Call out the empty-product base case first.
Raise a clear error for n < 0.
Avoid recursion-depth exceptions.
Show you know the production shortcut.
120 and 1 catch base-case mistakes fast.
Pro Tip: JavaScript ints do not overflow like C — talk about time/memory instead of fixed-width overflow.
Mistakes that commonly break factorial solutions.
Returning 0 or raising for n = 0.
→ Base case: n ≤ 1 returns 1.
Recursive calls never hit a base case for n < 0.
→ Validate and raise early.
Large n hits stack overflow.
→ Prefer iterative or BigInt factorial for big n.
Using i < n drops the last factor.
→ Use for (let i = 2; i <= n; i++).
JavaScript ints grow; talk about time/memory instead.
→ Mention arbitrary-precision integers explicitly.
JavaScript integers grow automatically, but recursion depth and runtime still matter.
n < 0Not defined in standard factorial; reject with a clear error.
0! and 1!Both equal 1 — your base case must cover them.
Large n can raise stack overflow; iterative code avoids this.
Numbers can be exact but enormous; printing and memory become expensive.
Accept only integers for this interview problem.
for (i = 2; i <= n; i++)Inclusive end so the last factor is included.
Handy follow-ups interviewers sometimes ask.
Try these variations to lock in the pattern.
Quick Takeaway: multiply 1 through n (with 0! = 1); use recursion to explain, loops (or BigInt factorial) to ship.
| Version | Time | Extra space |
|---|---|---|
| Recursive | O(n) multiplications | O(n) call frames |
| Iterative | O(n) multiplications | O(1) |
BigInt factorial | O(n) (implementation detail) | O(1) beyond result size |
Both approaches use Θ(n) arithmetic operations for exact n!; stack usage is the key difference. Result size grows with n and is excluded from the “extra space” column above.
Factorial multiplies 1 through n, with 0! = 1 by definition. Use recursion to match the recurrence, prefer an iterative loop (or BigInt factorial) when n grows, and always reject negatives.
Practice the three examples above, then continue to Fibonacci for the next classic sequence problem.
State the base case, explain O(n) time, and call out recursion-depth vs O(1) loop space.
BigInt factoriali < n in the loop by mistakeCompute n! the interview-friendly way.
0! = 1
Definitionn·(n-1)!
TheoryO(1) space
Practicen ≥ 0
EdgeΘ(n) ×
AnalysisStirling's approximation is often used to estimate how fast n! grows: n! ∼ √(2πn) · (n/e)n.
Learn iterative and recursive ways to print the Fibonacci sequence in JavaScript.
9 people found this page helpful