Recursion Basics
Ever heard of a function calling itself? That's recursion! It's like those Russian nesting dolls - each doll contains a smaller version of itself. In programming, a recursive function solves a problem by breaking it into smaller versions of the same problem until it hits a simple case it can solve directly.
Two things make recursion work: the base case and the recursive case. The base case is your stopping point - when to stop making smaller problems. The recursive case is where the magic happens - the function calls itself with a smaller input. Forget the base case? Infinite recursion. Stack overflow. Bad news.
Think of recursion like Russian dolls or those infinite mirror reflections. Each call is a smaller version of the problem, and eventually you hit the smallest version (base case) that you can solve without further recursion.
The Call Stack
Every recursive call adds a new layer to the call stack. Like stacking plates - you keep adding plates on top until you start removing them from the top. When you hit the base case, you start "unwinding" the stack, returning values back up. This is why recursion uses more memory than iteration.
When should you use recursion? When the problem naturally breaks into smaller subproblems - like tree traversals, divide-and-conquer algorithms, or solving puzzles. When the recursive solution is significantly cleaner than the iterative one. Don't use recursion just to show off - sometimes a simple loop is better.
function countdown(n) {
if (n <= 0) {
console.log("Done!");
return;
}
console.log(n);
countdown(n - 1);
}
countdown(5);
function sum(arr, index = 0) {
if (index === arr.length) return 0;
return arr[index] + sum(arr, index + 1);
}
console.log(sum([1, 2, 3, 4, 5]));
Try it Yourself โ