Skip to content

What is recursion and when should I actually use it?

I understand the textbook factorial example but I've never once used recursion in real code. When is it genuinely the right tool?
45
1 answers1.4K views

1 Answer

Accepted answer

RVRohan Verma7.6K XP1mo ago
Recursion is a function that calls itself on a smaller version of the same problem, with a base case that stops the descent. You've never used it in real code because most everyday programming is iteration over flat lists — and for flat lists, a loop is clearer. Recursion earns its place when the *data* is nested. Where it's genuinely the right tool: 1. Tree-shaped data. File systems (a folder contains files and folders), the DOM (an element contains elements), organisational charts, comment threads with replies, nested categories, JSON of unknown depth. You can't write a loop for 'unknown number of levels deep' cleanly, but recursion handles it in a few lines. 2. Traversing graphs — depth-first search is naturally recursive. 3. Divide-and-conquer algorithms: merge sort, quicksort, binary search. Each splits the problem in half and solves the halves the same way. 4. Parsing nested structures — expressions, markup, configuration formats. The concrete example that makes it click: rendering a comment thread where each comment can have replies, which can have replies. A recursive component or function that renders a comment then calls itself for each reply handles infinite depth. The iterative version needs an explicit stack and is markedly harder to read. The shape every recursive function needs: - A base case that returns without recursing (the empty folder, the leaf node, `n <= 1`). Missing or wrong base cases cause the stack overflow that makes people afraid of recursion. - A recursive step that moves *toward* the base case. If the subproblem isn't strictly smaller, it never terminates. The real costs, honestly: - Each call consumes stack space, so very deep recursion can crash. For deeply nested data or large n, iteration with an explicit stack is safer. JavaScript in particular has a modest stack limit and no reliable tail-call optimisation. - It can be slower than the equivalent loop due to call overhead. - Naive recursion can repeat work catastrophically — the classic recursive Fibonacci recomputes the same values exponentially many times. That's a solvable problem (memoisation), but it's a real trap. The practical rule: use recursion when the data structure is recursive; use a loop when it isn't. That single heuristic covers nearly every real decision. And don't feel bad about rarely reaching for it — a lot of professional developers write it a handful of times a year, mostly for exactly the tree-walking cases above.
97

Know the answer?

Join Nobink to answer, vote and build your reputation.