A parcel inside a parcel
A function calls itself: base case, recursive step, nested arrays and trees.
In JavaScript a function can call itself. Sounds like a magic trick, but it works like any other call: each call has its own parameters and its own return. Let's start with a countdown before a rocket launch — cats have been waiting for space for ages.
function countdown(n) {
if (n === 0) {
console.log("Liftoff!");
return;
}
console.log(n);
countdown(n - 1);
}
countdown(3);countdown(3) prints 3 and calls countdown(2), which calls countdown(1), which calls countdown(0), which just says "Liftoff!".Every correct recursion has two parts:
- the base case — a problem so simple the answer is known right away, with no new calls (
n === 0: time to launch); - the recursive step — the function solves the problem through the same problem, only smaller (
countdown(n - 1)).
Every step must bring you closer to the base case. Otherwise the unpacking never ends.
function unpack(box) {
return unpack(box + 1); // where does it stop?
}
try {
unpack(1);
} catch (error) {
console.log(error.name + ": " + error.message);
}try…catch catches the error so the example doesn't break the page. It gets its own chapter later; for now just look at the message.Recursion can return results too. The classic is the factorial: 5! = 5 × 4 × 3 × 2 × 1. Notice that 5! = 5 × 4!: the problem contains itself, just smaller. A perfect fit for recursion.
function factorial(n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5));
console.log(factorial(1));factorial(5) waits for factorial(4), which waits for factorial(3)… until factorial(1) returns 1. Then the answers travel back up: 2, 6, 24, 120.So far a loop could have done all of this. Recursion's real power is nested data. Here's an array holding arrays holding arrays — just like my boxes. How many fish are in the parcel in total? Array.isArray(x) tells a box from fish: it returns true only if x is an array.
function countFish(box) {
let total = 0;
for (const item of box) {
if (Array.isArray(item)) {
total += countFish(item); // a box: unpack it the same way
} else {
total += item; // fish: just count them
}
}
return total;
}
const parcel = [2, [3, 1], [[4], 5]];
console.log(countFish(parcel));These "boxes in boxes" are everywhere: folders in folders, replies to comments, menus with submenus, product categories. They're called trees: every node can have children, and the children have their own children. A node with no children (a file, a comment with no replies) is the natural base case.
const menu = [
{ title: "Home" },
{
title: "Catalog",
children: [
{ title: "Food" },
{ title: "Toys", children: [{ title: "Mice" }, { title: "Balls" }] },
],
},
{ title: "Contact" },
];
function printMenu(items, indent) {
for (const item of items) {
console.log(indent + item.title);
if (item.children) printMenu(item.children, indent + " ");
}
}
printMenu(menu, "");for loop — simpler and safer. But for a tree of unknown depth, recursion is the clearest tool there is. My motto: the shape of the data suggests the shape of the code.Pop quiz
Mistakes are fine: keep trying until you find the right answer, and Byte explains why it's right.