Recursion
ELI5 — The Vibe Check
Recursion is when a function calls itself to solve a smaller version of the same problem, like a set of Russian nesting dolls. You open a doll (call the function), inside is a smaller doll (call it again), and you keep going until you reach the tiniest doll (the base case). Without the tiny doll, you get a stack overflow.
Real Talk
Recursion is a technique where a function calls itself with a modified argument, solving progressively simpler sub-problems until reaching a base case that does not recurse. Recursive solutions are elegant for hierarchical data (trees, graphs), divide-and-conquer algorithms (merge sort, quicksort), and backtracking problems. Each call adds a frame to the call stack, so deep recursion risks stack overflow.
Show Me The Code
// Classic recursion: factorial
function factorial(n) {
if (n <= 1) return 1; // BASE CASE — stop here!
return n * factorial(n - 1); // recursive call with smaller n
}
factorial(5); // 5 * 4 * 3 * 2 * 1 = 120
// Recursive tree traversal:
function sumTree(node) {
if (!node) return 0; // base case: null node = 0
return node.value + sumTree(node.left) + sumTree(node.right);
}
When You'll Hear This
"Use recursion to traverse the file tree." / "You forgot the base case — that's why it's stack overflowing."
Related Terms
Algorithm
An algorithm is just a step-by-step recipe for solving a problem. Sort a list? There is an algorithm. Find the shortest path? Algorithm. Make a sandwich?
Loop
A loop makes your code do something over and over until a condition says stop.
Stack Overflow
A stack overflow happens when a function keeps calling itself forever, like a mirror facing a mirror.
Tree
A tree is a data structure shaped like an upside-down tree — one root at the top, branches going down, and leaves at the very bottom.