Functions
Recursion
A function that solves a problem by calling itself for the same problem, only smaller.
Why it exists
Lots of data is nested: a folder holds files and folders, a comment holds replies that are comments too, a menu item holds a submenu. The depth isn't known in advance, so you can't write the right number of nested loops. Recursion handles it naturally: the function deals with one level and hands every nested level to itself. The code follows the shape of the data — and comes out short and clear.
Where it's used
- Trees: the size of a folder with subfolders, comment threads with replies, menus with submenus, product categories.
- Nested data from an API: walk JSON of unknown depth, find every value under a given key.
- Browsers and frameworks: walking the DOM tree, rendering nested React components.
- Divide-and-conquer algorithms: quicksort, merge sort, trying out combinations.
Syntax
function solve(problem) {
if (problem is simple) return answer; // base case
return … solve(smaller problem) …; // recursive step
}Examples
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
factorial(5); // → 120function sumNested(items) {
let total = 0;
for (const item of items) {
total += Array.isArray(item) ? sumNested(item) : item;
}
return total;
}
sumNested([1, [2, 3], [[4], 5]]); // → 15
sumNested([]); // → 0 — the loop never ran: base caseconst menu = {
title: "Catalog",
children: [
{ title: "Food", children: [] },
{ title: "Toys", children: [{ title: "Mice", children: [] }] },
],
};
function menuDepth(item) {
let deepest = 0;
for (const child of item.children) {
deepest = Math.max(deepest, menuDepth(child));
}
return deepest + 1;
}
menuDepth(menu); // → 3function range(from, to) {
if (from > to) return [];
return [from, ...range(from + 1, to)];
}
range(1, 4); // → [1, 2, 3, 4]Results after // → aren't just written down — an automatic check runs and verifies them before every site update.
Why it works this way
A recursive call is an ordinary function call. The calling function is paused and waits for the answer, and the engine puts a note about it on the call stack: its variables and where to return to. Every call has its own parameters and local variables — n in factorial(5) and n in factorial(4) have nothing to do with each other.
When a call reaches the base case, it returns an answer without making new calls. The stack starts to unwind: each waiting call gets its answer, finishes its own result and returns it to the call waiting beneath it.
The call stack is limited — usually on the order of ten thousand calls; the exact number depends on the engine. If there's no base case, or a step doesn't get closer to it, the stack overflows and JavaScript throws RangeError: Maximum call stack size exceeded.
Any recursion can be rewritten as a loop with its own array used as a stack: recursion simply gets that stack from the engine for free.
Traps
How it differs from…
forloopFor flat data a loop is simpler, faster and never hits the stack limit. Recursion wins when the data is nested and its depth isn't known in advance.