Recursion Explained with Examples

Introduction:
In the hash tables lesson we promised to look at recursion next. Recursion is the technique behind tree traversals, merge sort and quick sort, binary search, backtracking and dynamic programming. Once it “clicks”, a whole family of problems that look hard becomes short and natural to solve.
Recursion means a function that calls itself. Instead of solving a big problem in one go, the function solves a small part of it and hands the rest, a smaller version of the same problem, to another call of itself. This continues until the problem becomes so small that the answer is obvious.
A real-life example: imagine you are standing in a long queue and want to know your position. You can’t see the front, so you ask the person in front of you, “What’s your position?” They ask the person in front of them, and so on. The first person in the queue knows the answer: 1. Each person then adds 1 and passes the answer back. That is recursion: the same question passed along, a simple stopping point, and answers built up on the way back.
The Two Parts of Every Recursive Function
Every correct recursive function has two parts:
- Base case: the smallest version of the problem, which is answered directly without another recursive call. It is what stops the recursion.
- Recursive case: the function calls itself with a smaller input, moving one step closer to the base case.
function countdown(n) {
if (n === 0) { // base case
console.log("Liftoff!");
return;
}
console.log(n);
countdown(n - 1); // recursive case
}
countdown(3);
// 3
// 2
// 1
// Liftoff!
If you forget the base case, or the input never gets smaller, the function calls itself forever, as we will see below.
How Recursion Works: The Call Stack
When a function is called, JavaScript puts a frame for it on the call stack. The frame stores that call’s own variables and where to return to. When the function returns, its frame is removed. With recursion, many frames of the same function sit on the stack at once, each with its own value of n.
Let’s trace the classic example, the factorial: 5! = 5 × 4 × 3 × 2 × 1.
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // recursive case
}
console.log(factorial(5)); // 120
Here is what happens on the call stack:
factorial(5) waits for factorial(4)
factorial(4) waits for factorial(3)
factorial(3) waits for factorial(2)
factorial(2) waits for factorial(1)
factorial(1) returns 1 <- base case
factorial(2) returns 2 * 1 = 2
factorial(3) returns 3 * 2 = 6
factorial(4) returns 4 * 6 = 24
factorial(5) returns 5 * 24 = 120
The calls go down until they reach the base case, and then the answers come back up, each call finishing its multiplication. This “wind down, then unwind” pattern is the key to understanding any recursive function.
How to Think Recursively
Writing recursive code becomes much easier with a simple three-step recipe:
- Find the base case. What is the smallest input you can answer immediately? An empty array, a string of length 0 or 1, the number 0, a
nulltree node. - Trust the recursive call. Assume your function already works for a smaller input. Don’t trace every call in your head.
- Combine. Use the answer for the smaller input to build the answer for the whole input.
Let’s apply it. To sum an array: the sum of an empty array is 0 (base case); otherwise it is the first element plus the sum of the rest (trust and combine).
function sum(arr) {
if (arr.length === 0) return 0;
return arr[0] + sum(arr.slice(1));
}
console.log(sum([4, 8, 15, 16])); // 43
To reverse a string: a string of length 0 or 1 is its own reverse; otherwise reverse everything after the first character and put the first character at the end.
function reverse(str) {
if (str.length <= 1) return str;
return reverse(str.slice(1)) + str[0];
}
console.log(reverse("recursion")); // noisrucer
To check a palindrome: compare the first and last characters, then check the middle part.
function isPalindrome(s) {
if (s.length <= 1) return true;
if (s[0] !== s[s.length - 1]) return false;
return isPalindrome(s.slice(1, -1));
}
console.log(isPalindrome("racecar"), isPalindrome("hello")); // true false
Divide and Conquer
Recursion shines when a problem can be cut in half at every step. Instead of making the input smaller by one, we make it half as big, which gives O(log n) depth.
Fast power: to compute x to the power n, compute x to the power n/2 once and square it. This needs about log₂(n) multiplications instead of n.
function power(x, n) {
if (n === 0) return 1;
const half = power(x, Math.floor(n / 2));
return n % 2 === 0 ? half * half : half * half * x;
}
console.log(power(2, 10)); // 1024
Binary search, which we met in the searching algorithms lesson, is naturally recursive: look at the middle element, then search only the left half or the right half.
function binarySearch(arr, target, lo = 0, hi = arr.length - 1) {
if (lo > hi) return -1; // not found
const mid = Math.floor((lo + hi) / 2);
if (arr[mid] === target) return mid;
if (arr[mid] < target) return binarySearch(arr, target, mid + 1, hi);
return binarySearch(arr, target, lo, mid - 1);
}
console.log(binarySearch([1, 3, 5, 7, 9, 11], 9)); // 4
Merge sort and quick sort from the sorting algorithms lesson use the same idea: split the array, sort each part recursively, and combine.
Recursion on Trees
Trees are recursive by nature: every node’s left and right children are themselves the roots of smaller trees. That is why tree code is almost always recursive, as we saw in the binary tree and BST lesson. The base case is an empty tree (null).
const tree = {
value: 10,
left: { value: 5, left: { value: 2, left: null, right: null }, right: null },
right: { value: 15, left: null, right: { value: 20, left: null, right: null } },
};
// Height = 1 + the height of the taller subtree
function treeHeight(node) {
if (node === null) return 0;
return 1 + Math.max(treeHeight(node.left), treeHeight(node.right));
}
// In-order traversal: left subtree, node, right subtree
function inorder(node, out = []) {
if (node === null) return out;
inorder(node.left, out);
out.push(node.value);
inorder(node.right, out);
return out;
}
console.log(treeHeight(tree), inorder(tree)); // 3 [ 2, 5, 10, 15, 20 ]
The same pattern works for nested data that has no fixed depth, such as folders inside folders, comments with replies, or nested arrays:
function flatten(arr) {
const out = [];
for (const item of arr) {
if (Array.isArray(item)) out.push(...flatten(item));
else out.push(item);
}
return out;
}
console.log(flatten([1, [2, [3, [4]], 5]])); // [ 1, 2, 3, 4, 5 ]
Backtracking: Generating All Possibilities
Some problems ask for every possible arrangement or combination. Recursion handles this elegantly: choose one option, recursively solve the rest, then try the next option. This is called backtracking. Here we generate all permutations of a list:
function permutations(items) {
if (items.length <= 1) return [items];
const result = [];
items.forEach((item, i) => {
const rest = [...items.slice(0, i), ...items.slice(i + 1)];
for (const p of permutations(rest)) result.push([item, ...p]);
});
return result;
}
console.log(permutations(["a", "b", "c"]).map((p) => p.join("")));
// [ 'abc', 'acb', 'bac', 'bca', 'cab', 'cba' ]
Backtracking is used to solve Sudoku, the N-Queens puzzle, finding paths in a maze, and generating subsets.
The Danger: Repeated Work
Recursion can be very slow if the same sub-problem is solved again and again. The Fibonacci sequence (0, 1, 1, 2, 3, 5, 8, …) is the famous example: each number is the sum of the two before it.
let calls = 0;
function fib(n) {
calls++;
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
console.log(fib(25), calls); // 75025 242785
To compute fib(25) the function was called 242,785 times, because fib(23), fib(22) and the rest are recalculated over and over. The running time grows exponentially, roughly O(2ⁿ).
The fix is memoization: store each answer the first time you compute it (in a hash table, of course) and reuse it.
let calls2 = 0;
function fibMemo(n, memo = new Map()) {
calls2++;
if (n < 2) return n;
if (memo.has(n)) return memo.get(n);
const value = fibMemo(n - 1, memo) + fibMemo(n - 2, memo);
memo.set(n, value);
return value;
}
console.log(fibMemo(25), calls2); // 75025 49
Same answer, but only 49 calls instead of 242,785. Recursion plus memoization is the heart of dynamic programming.
Stack Overflow
Every recursive call uses a frame on the call stack, and the stack has a limited size. If there is no base case, or the recursion goes too deep, JavaScript throws an error:
function forever(n) {
return forever(n + 1); // no base case!
}
try {
forever(0);
} catch (e) {
console.log(e instanceof RangeError, e.message);
// true Maximum call stack size exceeded
}
In JavaScript the limit is usually around ten thousand frames, depending on the engine. So for very deep, simple problems, such as adding up the numbers from 1 to 100,000, a plain loop is the safer choice:
function sumTo(n) {
let total = 0;
for (let i = 1; i <= n; i++) total += i;
return total;
}
console.log(sumTo(100000)); // 5000050000
Recursion vs Iteration
- Use recursion when the problem or the data is naturally recursive: trees, graphs, nested structures, divide and conquer, and backtracking. The code is usually shorter and closer to the idea.
- Use a loop when the problem is a simple straight line (counting, summing, walking an array) or when the depth could be very large.
- Any recursive function can be rewritten with a loop and your own stack. Depth-first search is often written both ways.
Time and Space Complexity
- Time: roughly the number of calls multiplied by the work done in each call. Factorial makes n calls, so it is O(n). Naive Fibonacci makes about 2ⁿ calls; with memoization it is O(n).
- Space: recursion uses extra memory for the call stack, equal to the maximum depth. Factorial uses O(n) stack space, binary search O(log n), and a tree traversal O(h), where h is the height of the tree.
Conclusion:
Recursion solves a problem by solving a smaller version of the same problem. Every recursive function needs a base case that stops it and a recursive case that moves toward that base case. Think in three steps: find the base case, trust the recursive call, and combine the results. Recursion is the natural tool for trees, divide and conquer and backtracking, but watch out for repeated work (fix it with memoization) and very deep calls (use a loop instead).
In the next lesson we will build on memoization and learn dynamic programming, one of the most important techniques in algorithm design and coding interviews.


