Recursion in JavaScript
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.
Base case first
fact(0) = 1 answers without recursing — the anchor every chain must reach.
Shrink every step
fact(n) = n * fact(n-1) moves strictly toward base — non-shrinking steps recurse forever.
Mind the stack
Each live call holds a frame; ~10k+ depth overflows typical stacks — no TCO to save you (except Safari).
Name for resilience
const f = function rec(n) {...rec(n-1)...} survives f being reassigned — the inner name always resolves.
function fact(n) { if (n <= 1) return 1; return n * fact(n - 1);}console.log(fact(5));n calls doing O(1) work, but n live stack frames at depth.
Recommended resourcesAffiliate links · may earn us a commission
Recommended for learners
Practice what you learned
Re-implement each visualized algorithm in JavaScript yourself — building beats watching.