The factorial of a nonnegative integer n, written n!, is the product of every integer from 1 through n. By definition, 0! = 1.
Remember
n! = 1 × 2 × 3 × … × n (for n ≥ 1)
0! = 1
Example: 5!
5 × 4 × 3 × 2 × 1 = 120
Recurrence:
n! = n × (n − 1)!
with base case 0! = 1! = 1
n
Expansion
n!
0
(empty product)
1
1
1
1
5
5 × 4 × 3 × 2 × 1
120
6
6 × 5!
720
Approach
How to Find Factorial in JavaScript
Four clear steps — then pick a loop or recursion.
Reject negative inputs (factorial is not defined for them).
Treat 0 and 1 as the base case: return 1.
Multiply all integers from 2 through n (loop), or use n × (n − 1)! (recursion).
Remember Number is exact only through 20! — use BigInt beyond that.
Method
Idea
Time
Best for
Iterative loop
Multiply 2..n into a running product
O(n)
Production, large n, interviews
Recursion
n × Factorial(n − 1) with base ≤ 1
O(n)
Showing the recurrence clearly
Pseudocode
Pseudocode
function Factorial(n):
if n < 0:
error "not defined"
if n <= 1:
return 1
result = 1
for i from 2 to n:
result = result * i
return result
Reference
Cheat Sheet
Keep these facts handy while writing the program.
Topic
Detail
Definition
Product of 1..n; 0! = 1
Base cases
0 and 1 both return 1
Recurrence
n! = n × (n − 1)!
Number limit
Exact through 20! only
Negatives
Reject — undefined for integers
Classic check
5! → 120
Try it
Live Preview
Enter a nonnegative integer (0–20) to see the product chain and n!.
Whole numbers from 0 to 20 (exact in this preview). Tap a chip or type a value.
Result
n = 5
Chain: 1 × 2 × 3 × 4 × 5
5! = 120
Code
JavaScript Programs
Start with the iterative loop for interviews and real code. Use recursion when you want to show the recurrence clearly.
Example 1 — Iterative Loop
Multiply integers from 2 to n into a running product. No recursion-depth risk.
JavaScript
function factorial(n) {
if (n < 0) {
throw new Error("Factorial is not defined for negatives.");
}
let result = 1;
for (let i = 2; i <= n; i++) {
result *= i;
}
return result;
}
const number = 5;
console.log(number + "! = " + factorial(number));
Reject n < 0 — integer factorial is undefined there.
Start with result = 1 (covers both 0! and 1!).
Loop i from 2 to n and multiply into result.
For n = 5: 1 → 2 → 6 → 24 → 120.
Extra space is O(1) — prefer this style in real code.
Example 2 — Recursion
Direct translation of n! = n × (n − 1)! with base cases 0 and 1.
JavaScript
function factorial(n) {
if (n < 0) {
throw new Error("Factorial is not defined for negatives.");
}
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120
console.log(factorial(0)); // 1