Recursion = a function calling itself, each time with a smaller problem, until the problem is trivial. Two parts, always:
The anatomy
function factorial(n) {
if (n <= 1) return 1; // BASE CASE โ when to stop
return n * factorial(n - 1); // RECURSIVE CASE โ shrink the problem
}
// factorial(4) โ 4 ร 3 ร 2 ร 1 = 24Forget the base case โ infinite calls โ "Maximum call stack size exceeded". That error IS recursion's failure mode.
Trace it (the skill interviews test)
factorial(3)
= 3 * factorial(2)
= 2 * factorial(1)
= 1 โ base case hit
= 2 * 1 = 2
= 3 * 2 = 6 โ stack unwindsWhen recursion shines vs hurts
- Shines: trees, nested structures (folders, JSON, DOM), divide-and-conquer (merge sort)
- Hurts: plain counting โ naive
fib(40)makes ~1.6 billion calls. Iterate or memoize instead
Practice: Fibonacci on our judge deliberately times out naive recursion at n=40 โ beat it with iteration.