Factorial
The factorial of n is n × (n-1) × ... × 1, and 0! = 1. This is the
textbook recursion: n! = n × (n-1)!.
Same two pieces as countdown — base case first, then a smaller call:
function factorial(n) {
if (n <= 1) return 1; // base case: 0! and 1! are both 1
return n * factorial(n - 1); // recursive step
}
factorial(5); // 120
Notice the only real difference from countdown: here we multiply the result of the smaller call instead of putting it in an array.
Your task
Write factorial(n) that returns n!. Assume n >= 0.
⚡ 35 XP
🧱 Code blocks
Drag a block into the editor, or tap it to drop it in where your cursor is. Add them in order to build your answer.
solution.jsRuns in your browser
Loading editor…
Tests4 to pass
factorial(5) → 120
factorial(0) → 1
factorial(1) → 1
factorial(6) → 720
Run your code to check these.