Find Factorial in JavaScript

Beginner
⏱️ 8 min read
📚 Updated: Aug 2026
🎯 3 Code Examples
🚀 Live Preview
Recursion & loop

What You’ll Learn

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.

Definition

n! & 0!

Product 1…n; empty product gives 0! = 1.

Recurrence

n·(n-1)!

Classic recursive interview form.

Iterative

O(1) space

Loop multiply avoids recursion-depth limits.

BigInt

BigInt

Exact large factorials beyond the Number safe range.

Live Preview

n ≤ 20

Exact factorials in the browser for small n.

O(n)

Multiplies

Both styles use Θ(n) multiplications.

Introduction

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.

Why it matters?

It is the classic interview problem for base cases, recurrence vs loops, and recursion-depth tradeoffs.

Key Highlights

0! = 1

Empty product — say it clearly in interviews.

Recurrence

n! = n · (n-1)! for n ≥ 1.

Loop Safer

Iteration avoids recursion-depth errors.

No Negatives

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).

📝 Problem & Approach

Given a nonnegative integer n, compute n!.

JavaScript
# 0! = 1
# 5! = 5 * 4 * 3 * 2 * 1 = 120
# 6! = 6 * 5! = 720

Inputs & Outputs

ItemTypeDescription
nnumberNonnegative integer (reject negatives).
Return / printnumber / textExact value of n!.

Minimal workflow

Pseudocode
function factorial(n) {
  if (n <= 1) return 1;
  return n * factorial(n - 1);
}

Method comparison

MethodIdeaNotes
Recursiven * factorial(n-1)Matches theory; O(n) stack
IterativeMultiply 2…n in a loopO(1) extra space
BigInt factorialBigInt loopBest for production code

⚡ Quick Reference

GoalPattern
Base caseif n <= 1: return 1
Recurrencereturn n * factorial(n - 1)
Loopfor (let i = 2; i <= n; i++) result *= i
BigInt loopBigInt factorial(n)
Classic values0! = 1, 5! = 120, 10! = 3628800
Rejectn < 0 → raise / error

📋 Recursive vs Iterative vs BigInt

Three ways to compute n! — pick by clarity and constraints.

Recursive
n * f(n-1)

Teaches base case + recurrence

Iterative
loop *= i

Safer for large n (no stack depth)

BigInt
BigInt factorial

Optimized and battle-tested

Interview tip
both + tradeoff

Show recursion, then mention loop

Context

When This Problem Shows Up

Reach for factorial when products, permutations, or recursion drills appear.

  1. Interview warm-ups

    First recursion problem many candidates see.

  2. Combinatorics

    Permutations and combinations use n!.

  3. Teaching recursion

    Clear base case and single recursive call.

  4. Before Fibonacci

    Natural precursor to recursive sequences.

  5. Not for negatives

    Validate n ≥ 0 before computing.

Key benefit: one short function that forces clear thinking about base cases, space, and growth.

🔮 Live Preview

Exact factorial for 0 ≤ n ≤ 20 (safe to display exactly in JavaScript).

Try 0, 12, or 20. Values above 20 are blocked in this widget.

Live result
Press “Compute n!”.

Examples Gallery

Three complete JavaScript programs with Try it Yourself editors — recursive, iterative, and BigInt exact factorial. Click View Output to reveal sample console results.

📚 Getting Started

Base case + recurrence for interview explanations.

Example 1 — Recursive Factorial

Classic recursive style with input validation.

JavaScript
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}`);

How It Works

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.

⚡ Iterative Style

Same numeric result with O(1) auxiliary space.

Example 2 — Iterative Factorial

No recursion-depth risk; multiply factors from 2 to n.

JavaScript
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)}`);

How It Works

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.

⚙️ BigInt Style

Exact integers when Number is no longer safe.

Example 3 — Exact Factorial with BigInt

Compute exact large factorials beyond the Number safe range.

JavaScript
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)}`);
}

How It Works

Prefer BigInt when exact large factorials are required. In interviews, write recursive or iterative yourself first, then mention BigInt for production-scale exact values.

🧠 How the Algorithm Computes

1

Validate

Reject n < 0; factorial is not defined for negatives.

Guard
2

Base case

If n ≤ 1, return 1 (covers 0! and 1!).

Stop
3

Recurrence or loop

Compute n * factorial(n-1), or multiply 2…n.

Product
=

n!

Exact product for nonnegative n.

🔎 Worked Walkthrough — n = 5

Trace the recursive expansion for the classic interview value.

CallExpressionReturns
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)base1
unwind2*1 … 5*24120

Final answer: 5! = 120.

Use Cases

Where factorial shows up beyond the interview prompt.

1. Interview Warm-Ups

Base case, recurrence, and loop tradeoffs.

Example: write factorial(n).

2. Permutations

n! counts orderings of n items.

Example: 5 books → 120 orders.

3. Combinations

C(n, k) uses factorials in the formula.

Example: n! / (k!(n-k)!).

4. Teaching Recursion

Single recursive call with a clear stop.

Example: chalkboard unwind of 5!.

5. Before Fibonacci

Warm-up for recursive series problems.

Example: next page in this chain.

6. Growth Awareness

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.

Advantages

Why this pattern works well in interviews and classwork.

  1. 1. Clear Math

    One recurrence and one base case tell the whole story.

  2. 2. Two Valid Styles

    Recursion matches theory; loops scale better.

  3. 3. Famous Test Cases

    0, 1, 5, and 20 are easy to verify.

  4. 4. BigInt for Large n

    BigInt factorial is ready for production use.

Pro Tip: show recursion for the whiteboard, then say you would ship the iterative or BigInt version.

Usage Tips

Small habits that keep factorial solutions interview-ready.

  1. 1. State 0! = 1

    Call out the empty-product base case first.

  2. 2. Validate Negatives

    Raise a clear error for n < 0.

  3. 3. Prefer Loops for Large n

    Avoid recursion-depth exceptions.

  4. 4. Mention BigInt factorial

    Show you know the production shortcut.

  5. 5. Spot-Check 5 and 0

    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.

Common Pitfalls

Mistakes that commonly break factorial solutions.

  1. 1. Forgetting 0!

    Returning 0 or raising for n = 0.

    → Base case: n ≤ 1 returns 1.

  2. 2. Accepting Negatives Silently

    Recursive calls never hit a base case for n < 0.

    → Validate and raise early.

  3. 3. Deep Recursion Only

    Large n hits stack overflow.

    → Prefer iterative or BigInt factorial for big n.

  4. 4. Off-by-One in the Loop

    Using i < n drops the last factor.

    → Use for (let i = 2; i <= n; i++).

  5. 5. Worrying About C-style Overflow

    JavaScript ints grow; talk about time/memory instead.

    → Mention arbitrary-precision integers explicitly.

Edge Cases

JavaScript integers grow automatically, but recursion depth and runtime still matter.

Negative

n < 0

Not defined in standard factorial; reject with a clear error.

Zero / one

0! and 1!

Both equal 1 — your base case must cover them.

Recursion

Deep recursion

Large n can raise stack overflow; iterative code avoids this.

Huge output

Very large factorials

Numbers can be exact but enormous; printing and memory become expensive.

Validation

Non-integer input

Accept only integers for this interview problem.

Loop bound

for (i = 2; i <= n; i++)

Inclusive end so the last factor is included.

⚖️ Facts Worth Knowing

Handy follow-ups interviewers sometimes ask.

  • Formal. 0! = 1 and n! = n · (n-1)! for n ≥ 1; equivalently ∏k=1n k.
  • Permutations. n! counts ways to order n distinct objects.
  • Growth. Each step multiplies by n, so values explode quickly.
  • Stirling. Approximate growth with √(2πn) · (n/e)n.

🎯 Practice Problems

Try these variations to lock in the pattern.

1. Verify classics

  • 0! = 1, 5! = 120
  • 10! = 3628800

2. Match both styles

  • Recursive vs iterative
  • Assert identical results

3. Reject negatives

  • Throw an error for n < 0
  • Write a short unit test

4. Print the expansion

  • Show 5 * 4 * 3 * 2 * 1
  • Then the final value

Notes

  • Definition: 0! = 1 and n! = n·(n-1)! for n ≥ 1.
  • Code: recursion matches theory; iteration avoids recursion-depth limits.
  • Watch-outs: validate negatives; prefer loops for very large n.
  • Both styles use Θ(n) multiplications; stack usage is the key difference.

Quick Takeaway: multiply 1 through n (with 0! = 1); use recursion to explain, loops (or BigInt factorial) to ship.

⏱️ Time and Space Complexity

VersionTimeExtra space
RecursiveO(n) multiplicationsO(n) call frames
IterativeO(n) multiplicationsO(1)
BigInt factorialO(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.

Wrap Up

🎉 Conclusion

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.

💡 Best Practices

✅ Do

  • State 0! = 1 up front
  • Validate n ≥ 0
  • Show recursive and iterative
  • Prefer loops for large n
  • Mention BigInt factorial

❌ Don’t

  • Return 0 for 0!
  • Recurse on negatives
  • Ignore recursion-depth limits
  • Use i < n in the loop by mistake
  • Assume C-style int overflow

Key Takeaways

Knowledge Unlocked

Five things to remember about factorial

Compute n! the interview-friendly way.

5
Core concepts
r 02

Recur

n·(n-1)!

Theory
i 03

Iterate

O(1) space

Practice
- 04

Guard

n ≥ 0

Edge
O 05

Cost

Θ(n) ×

Analysis

❓ Frequently Asked Questions

For a nonnegative integer n, n! is the product of all integers from 1 through n. By definition, 0! = 1.
Both 0! and 1! equal 1. Those cases terminate the recurrence n! = n * (n-1)!.
IEEE doubles represent integers exactly only up to Number.MAX_SAFE_INTEGER (2^53-1). Since 21! exceeds that, exact n! as Number fits only for n <= 20; use BigInt for larger exact values.
Both run O(n) multiplications. Recursion uses O(n) call stack space; a loop uses O(1) extra space and avoids stack overflow for moderately large n.
Factorial is not defined for negative integers in the standard combinatorial sense. Validate n >= 0 before computing.
Computing n! with n multiplications costs O(n) time. Space is O(n) for recursion depth or O(1) for iterative loop, excluding result size.
Yes when you need exact integers beyond the Number safe range. In interviews, write recursive or iterative yourself first, then mention BigInt.
It is the empty product, and it makes the recurrence n! = n*(n-1)! work for n = 1.
Use the Try it Yourself links under each code sample — they open an in-browser editor with the same logic so you can edit the input and Run.

Did you Know? 🔊

Stirling's approximation is often used to estimate how fast n! grows: n! ∼ √(2πn) · (n/e)n.

Continue to Fibonacci Series

Learn iterative and recursive ways to print the Fibonacci sequence in JavaScript.

Fibonacci tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

9 people found this page helpful