Learn JavaScript
❯ functions.recursion

Recursion in JavaScript

$concept

Recursion solves problems with functions calling themselves on smaller inputs: a base case answering directly plus a recursive step shrinking toward it. Tree walks (DOM traversal!), divide-and-conquer, and nested-data processing read almost as their definitions.

Every call consumes stack space, and JavaScript engines offer no guaranteed tail-call optimization (Safari excepted in practice) — depth is bounded (tens of thousands), the base case is load-bearing, and deep linear problems belong in iteration. Named function expressions (const f = function rec() {}) keep recursion working even when bindings reassign.

$how it works
1

Base case first

fact(0) = 1 answers without recursing — the anchor every chain must reach.

2

Shrink every step

fact(n) = n * fact(n-1) moves strictly toward base — non-shrinking steps recurse forever.

3

Mind the stack

Each live call holds a frame; ~10k+ depth overflows typical stacks — no TCO to save you (except Safari).

4

Name for resilience

const f = function rec(n) {...rec(n-1)...} survives f being reassigned — the inner name always resolves.

$example
function fact(n) {
if (n <= 1) return 1;
return n * fact(n - 1);
}
console.log(fact(5));
Output
120
1fact(5) misses base, returning 5 * fact(4) down to fact(1).
2fact(1) hits base returning 1 — unwinding begins.
3Products fold back up to 120.
$complexity
time O(n)
space O(n)

n calls doing O(1) work, but n live stack frames at depth.

$use cases
DOM and JSON tree traversal
Divide-and-conquer (mergesort, binary search)
Backtracking and combinatorial exploration
Rewriting deep linear recursion as iteration

Recommended resourcesAffiliate links · may earn us a commission

Recommended for learners

Structured coding coursesVideo courses that pair well with visual practice — pick one language and go deep.Browse courses Pro code editor & AI assistantWrite, debug and explain code faster while you practice the patterns here.Try it free Classic DSA interview booksThe reference books interviewers themselves learned from — great next to the visualizers.See the books

Practice what you learned

Re-implement each visualized algorithm in JavaScript yourself — building beats watching.