Skip to content

Recursion

Medium — good to knowGeneral Dev

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."

Made with passive-aggressive love by manoga.digital. Powered by Claude.