Recursion is when a function solves a problem by calling itself on a smaller version of the same problem. Each call handles one slice, then hands the rest to another call.
Every recursive function needs two ingredients. First, a base case: an input small enough to answer directly, with no further call. Second, a recursive step that shrinks the problem and calls itself, moving steadily toward that base case.
Miss either one and it breaks. Without a base case the calls never stop. Without real progress toward it, you also never stop.
A factorial shows both parts clearly:
function fact(n) {
if (n <= 1) return 1; // base case
return n * fact(n - 1); // shrinks toward base
}
// fact(4) === 24
This answer doesn't lend itself to a diagram - it reads best . No credits were charged.
Why there's no diagram: “”
The interactive diagram is below the answer - jump to diagram ↓ · Below it, the related concept . Jump to it ↓
The diagram below the answer is the concept . Jump to it ↓