Compute a factorial recursively
Implement factorial(n) recursively so that it returns n! for a non-negative integer n. factorial(5) returns 120, and factorial(0) returns 1 (the base case).
function factorial(n) {
// your code here
}
Write the implementation.
Base case: when n is 0 (or 1), return 1. Recursive case: return n * factorial(n - 1). Each call multiplies n by the factorial of n - 1 until the base case stops the recursion. The base case at 0 is what makes factorial(0) correctly yield 1.
- ✗Omitting the base case, causing infinite recursion and a stack overflow
- ✗Recursing toward
n + 1instead ofn - 1, so it never terminates - ✗Returning
0for the base case, which zeroes out the whole product
- →Why does a missing base case cause a
RangeErrorstack overflow? - →How would you rewrite this iteratively to avoid deep recursion?
Solution
The base case stops the recursion at 0; the recursive case multiplies n by the factorial of n - 1.
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
How it works
The recursion defines n! as n * (n - 1)!. Each call decrements n by one and multiplies it by the result of the call for n - 1. The base case n === 0 returns 1 and stops the descent — without it the recursion would never terminate and would overflow the call stack.
For example, factorial(3) unwinds to 3 * 2 * 1 * 1 = 6. The base case at 0 also correctly yields factorial(0) === 1. </content>