What is recursion?

Recursion is when a function solves a problem by calling itself on a smaller version of the same problem, stopping at a base case that can be answered directly.

The two parts every recursive function needs

  1. Base case: the simplest input, answered without recursion. Without it the function never stops and the stack overflows.
  2. Recursive case: break the problem down and call the function on the smaller piece, making progress towards the base case.

Where recursion is natural

  • Tree-shaped data: nested comments, file systems, menus, the DOM, JSON of unknown depth.
  • Divide and conquer: merge sort, quicksort, binary search.
  • Backtracking: permutations, sudoku, path finding.
  • Deep clone, deep equality and flattening nested arrays.

Limits in JavaScript

  • Each call adds a stack frame. Very deep recursion (tens of thousands of levels) throws RangeError: Maximum call stack size exceeded.
  • Tail call optimisation is in the spec but only Safari implements it, so do not rely on it.
  • For very deep or performance-critical cases, convert to a loop with an explicit stack or queue.

Making it efficient

Naive recursion can repeat work. Fibonacci is the classic example: fib(40) makes hundreds of millions of calls. Memoization (caching results) fixes that.

Code example

js
1// Base case + recursive case
2function factorial(n) {
3 if (n <= 1) return 1; // base case
4 return n * factorial(n - 1); // smaller problem
5}
6console.log(factorial(5)); // 120
7
8// Natural fit: tree-shaped data
9const fileTree = {
10 name: "src",
11 children: [
12 { name: "index.js" },
13 { name: "components", children: [{ name: "Button.js" }, { name: "Modal.js" }] },
14 ],
15};
16const countFiles = (node) => (node.children ? node.children.reduce((n, c) => n + countFiles(c), 0) : 1);
17console.log(countFiles(fileTree)); // 3
18
19// Memoization turns exponential into linear
20const memo = new Map();
21function fib(n) {
22 if (n < 2) return n;
23 if (memo.has(n)) return memo.get(n);
24 const value = fib(n - 1) + fib(n - 2);
25 memo.set(n, value);
26 return value;
27}
28console.log(fib(50)); // 12586269025
29// (beyond fib(78) results exceed Number.MAX_SAFE_INTEGER - use BigInt for those)
30
31// Same traversal without recursion (explicit stack) for very deep data
32function countFilesIterative(root) {
33 let count = 0;
34 const stack = [root];
35 while (stack.length) {
36 const node = stack.pop();
37 if (node.children) stack.push(...node.children);
38 else count++;
39 }
40 return count;
41}
42console.log(countFilesIterative(fileTree)); // 3

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app