concept / 001

Recursion

A function that calls itself β€” until it doesn't. Let's see exactly how that works.

πŸͺ†
Russian Dolls
Each doll contains a smaller version of itself, until you hit the tiny solid one at the center.
πŸͺž
Mirror in Mirror
Two mirrors facing each other create infinite reflections β€” but a real recursion always stops.
πŸ§—
Climbing Stairs
"How many steps to the top?" = 1 + (how many steps from the next one). Same problem, smaller.

πŸ›‘ Base Case

The stopping condition. Without this, the function calls itself forever and crashes. It's the tiny solid doll at the center β€” no more recursion here.

πŸ”„ Recursive Case

The function calls itself with a smaller input. Each call must move closer to the base case, or you'll recurse forever.

factorial.js
// 5! = 5 Γ— 4 Γ— 3 Γ— 2 Γ— 1 = 120

function factorial(n) {

  // πŸ›‘ BASE CASE β€” stop here
  if (n === 0) {
    return 1;
  }

  // πŸ”„ RECURSIVE CASE β€” call myself with a smaller n
  return n * factorial(n - 1);
}

factorial(4); // β†’ 24
factorial(
)

πŸ“₯ Call Stack

β€” empty β€”

πŸ“‹ Execution Log

♾️

Infinite recursion (stack overflow)

If your base case is never reached β€” maybe because n goes negative instead of reaching 0 β€” the function calls itself forever until the browser crashes with a "Maximum call stack size exceeded" error.

🐌

Redundant work without memoization

Naive recursive Fibonacci recalculates the same values over and over. fib(30) might make over a billion calls. The fix: cache results (memoization) or switch to iteration.