What is recursion?
By FrontendPro Editorial Team Updated 9/26/2026
Answer
A recursive function calls itself on a smaller version of the problem, until it reaches a case simple enough to answer directly.
Every recursive function needs two things: a base case that returns without recursing, and a step that moves towards it. Miss either and you get infinite recursion.
function factorial(n) {
if (n <= 1) return 1; // base case
return n * factorial(n - 1); // moves towards it
}
Where it genuinely helps
Recursion fits data that is itself nested, where a loop would need its own stack:
function flatten(value) {
return Array.isArray(value) ? value.flatMap(flatten) : [value];
}
function walk(node, fn) {
fn(node);
node.children?.forEach((child) => walk(child, fn));
}
DOM traversal, JSON trees, file systems, comment threads and menu structures all have this shape. For a flat list, a loop is simpler and faster — recursion is not a goal in itself.
The stack limit is real
Each call consumes a stack frame, and browsers allow roughly 10,000 before throwing RangeError: Maximum call stack size exceeded. Recursing over a large array will hit it.
Note that JavaScript engines do not implement tail-call optimisation despite it being in the spec — Safari is the only exception. Writing your recursion in tail position does not save you.
For deep or unbounded structures, convert to an explicit stack:
function walkIterative(root, fn) {
const stack = [root];
while (stack.length) {
const node = stack.pop();
fn(node);
stack.push(...(node.children ?? []));
}
}
One more caution
Naive recursion can repeat work exponentially — the classic recursive Fibonacci recomputes the same values over and over. Memoise, or use iteration, when subproblems overlap.
