Recursion is a problem-solving strategy where a function solves a big problem by calling itself on a smaller version of the same problem, until the version is so small the answer is obvious. Every recursive function needs exactly two ingredients: a base case, the tiny problem you can answer directly without recursing, and a recursive case, which shrinks the problem and trusts the same function to handle the rest.
It feels like magic the first time, but the machinery is mundane: the call stack. Each call gets a frame holding its own local variables, and frames pile up while calls are pending. The stack "unwinds" as base cases return and results combine on the way back up. This is also why infinite recursion crashes: each pending frame consumes memory, so 100,000 un-returned calls exhaust the stack, the famous stack overflow.
Factorial: the classic first example
function factorial(n) {
// Base case: 0! and 1! are 1, answer directly
if (n <= 1) return 1;
// Recursive case: n! = n × (n-1)!, smaller problem, trust the function
return n * factorial(n - 1);
}
factorial(4); // 24
// Call stack grows: factorial(4) → factorial(3) → factorial(2) → factorial(1)
// Then unwinds: 1 → 2 → 6 → 24How to design any recursive function
- 1
Find the base case
What is the smallest input where the answer is trivial? For list problems it's often an empty list; for numbers, 0 or 1. Without a base case, or if the recursion can never reach it, you get a stack overflow.
- 2
Shrink the problem
The recursive call must make progress toward the base case, a smaller number, a shorter list, a subtree. If the argument doesn't shrink, the base case is unreachable.
- 3
Combine the results
Decide how the smaller answer builds the bigger answer: multiply, add, concatenate, merge two sorted halves. This combining step is where each algorithm's personality lives.
- 4
Trust the recursion
Assume the recursive call already works correctly for smaller inputs (this is the recursive leap of faith). Debug one level at a time, not the whole tree at once.
Where recursion genuinely wins
// Sum all values in a binary tree.
// Iterative version needs an explicit stack/queue to track pending nodes;
// recursion gets that bookkeeping for free from the call stack.
function treeSum(node) {
if (node === null) return 0; // base case: empty subtree
return node.value // this node's contribution
+ treeSum(node.left) // trust recursion on the left subtree
+ treeSum(node.right); // ...and the right subtree
}