Recursion on nested data

Solve it by solving a smaller one

Lesson 4 of 20 · 11 min · Module 1: Functions, deeper

Menus, folders, and comment threads nest inside each other to any depth. A recursive function, one that calls itself, handles every level with the same few lines.

Start this lesson →

Free. No installation: you write and run the code in your browser, and it is checked automatically.

By the end, you’ll be able to…

  • Identify a base case and a recursive case
  • Walk nested arrays of any depth
  • Sum values in a tree

The idea

Every recursive function needs a base case that stops, and a recursive case that works on a smaller piece. For nested arrays, a non-array value is the base case; an array means "handle each item the same way".

function countdown(n) {
  if (n === 0) return ["liftoff"];
  return [n, ...countdown(n - 1)];
}
console.log(countdown(3));

01Trust the smaller call

When flatten meets [2, [3]], it does not need to know how deep that goes. It asks flatten to handle it and spreads the result in. Each call handles one level.

02Base cases stop the recursion

A plain value is pushed as it is. Without a base case, a function would call itself forever and crash with "Maximum call stack size exceeded".

function depth(x) {
  return Array.isArray(x) ? 1 + Math.max(0, ...x.map(depth)) : 0;
}
console.log(depth([1, [2, [3]]]));
Output
3

03Missing children

node.children ?? [] treats a missing children list as empty. The recursion then ends naturally at leaf nodes.

Your turn

Write flatten(items) that flattens arrays nested to any depth, without using .flat(). Write treeTotal(node) for nodes shaped like { value: 5, children: [ ... ] }, returning the sum of every value in the tree; children may be missing.

What the checks look for

  • Flattens deeply nested arrays
  • Handles empty arrays and keeps other values
  • Does not use .flat()
  • Sums a whole tree
Try it in the editor →

Take this with you

Recursion matches nested data: handle one level, delegate the rest.

Go a little further

Write findPath(node, value) that returns the list of values from the root down to the node containing value.

Learn JavaScript Intermediate for free

20 short lessons with real code and instant checks.

See the whole course →