Recursion
Functions calling themselves.
A function can call itself. That's called recursion. It's a neat way to solve problems that contain smaller copies of themselves, like counting down, or exploring folders inside folders.

- A function calls itself
- Recursion
- Problems inside problems
Countdown and factorial
Countdown prints N, then calls itself with N minus one. The base case, N equals zero, stops it. Factorial multiplies N by the factorial of N minus one, until N reaches one. Run it.
function countdown(n) {
if (n === 0) {
console.log("Lift off!");
return;
}
console.log(n);
countdown(n - 1);
}
countdown(3);
const factorial = n => (n <= 1 ? 1 : n * factorial(n - 1));
console.log("5! =", factorial(5));3 2 1 Lift off! 5! = 120
Always have a base case
Every recursive function needs a base case, a condition where it stops calling itself. Without one, it calls itself forever, until JavaScript runs out of room and throws a range error, maximum call stack size exceeded. Each call should move closer to the base case.
| key | value |
|---|---|
| Recursive case | calls itself, smaller |
| Base case | stops |
| No base case | stack overflow |
| Good for | nested data |
Summing nested lists
Recursion shines with data that's nested inside itself. Here, a list can contain numbers, or more lists. Sum all adds up the numbers. When it finds a list, it calls itself on that list. However deep the nesting goes, the same few lines handle it. Run it.
function sumAll(items) {
let total = 0;
for (const item of items) {
if (Array.isArray(item)) total += sumAll(item);
else total += item;
}
return total;
}
console.log(sumAll([1, [2, 3], [4, [5, [6]]]]));21
Summary
Recursion is a function calling itself, with a base case to stop. Next, pure functions.
Key takeaways- Call yourself
- Base case stops it
- Move towards it