Recursion is when a function calls itself to solve a smaller version of the same problem, until it reaches a simple case it can answer directly. It's a different way of expressing repetition than a loop — sometimes more natural, especially for problems that are naturally defined in terms of themselves.
The factorial of a number is that number multiplied by the factorial of the number below it, until you reach 1. For example, 4! = 4 × 3 × 2 × 1 = 24.
function factorial(n) {
if (n <= 1) {
return 1; // base case — stops the recursion
}
return n * factorial(n - 1); // recursive case
}
console.log(factorial(4)); // 24| Part | Purpose |
|---|---|
| Base case | The simple case that returns an answer directly, with no further recursion — without this, the function calls itself forever |
| Recursive case | Calls the function again on a smaller version of the problem, moving toward the base case |
A recursive function with no base case (or one that's never reached) causes a "stack overflow" — the program runs out of memory tracking all the pending calls. Every recursive function needs a way to eventually stop.