Skip to content

Looping & Recursion

There are two ways to repeat work in JavaScript. A loop repeats a block of code in place. Recursion repeats it by having a function call itself, each time with a smaller piece of the problem, until it reaches a case simple enough to answer directly. Anything one can do, the other can too, but each fits some problems better.

The loop keeps its state in a counter. The recursive function keeps it in its argument, and stops at the base case, which is the condition under which it returns without calling itself again:

for (let n = 3; n > 0; n--) {
console.log(`loop ${n}`);
}
function countdown(n) {
if (n === 0) {
return;
}
console.log(`recursion ${n}`);
countdown(n - 1);
}
countdown(3);

This prints:

loop 3
loop 2
loop 1
recursion 3
recursion 2
recursion 1

For a simple count like this, the loop is clearer and cheaper.

Recursion suits data that contains smaller copies of itself, such as folders within folders, comments with replies, or a menu with submenus. A loop alone cannot know how deep the nesting goes, but a function that handles one level and calls itself for the level below handles any depth:

const folder = {
name: 'docs',
size: 4,
children: [
{ name: 'cv.pdf', size: 120 },
{
name: 'photos',
size: 4,
children: [
{ name: 'beach.jpg', size: 900 },
{ name: 'park.jpg', size: 750 },
],
},
],
};
function totalSize(item) {
let total = item.size;
for (const child of item.children ?? []) {
total += totalSize(child);
}
return total;
}
console.log(totalSize(folder));

This prints:

1778

The base case here is an item with no children, which returns its own size. The ?? operator supplies an empty array for such an item, so the loop runs no passes.

Every call that has not yet returned takes a frame on the call stack, and the stack has a fixed size. A recursive function that never reaches its base case, or recurses very deeply, runs out of room:

function depth(n) {
return depth(n + 1);
}
try {
depth(0);
} catch (error) {
console.log(error.name, error.message);
}

This prints:

RangeError Maximum call stack size exceeded

The limit depends on the engine and on the size of each frame, and in Node a simple function reaches it after roughly ten thousand calls. The language specification describes tail-call optimisation, which would remove the limit for some recursive functions, but Safari is the only major engine that implements it, so code should not depend on it. For a long, flat sequence, use a loop.

A loop runs to the end without pausing. If its body starts something asynchronous, such as fetch(), a timer or a database query, the loop gets back a promise and moves straight on. The results arrive later, after the loop and the code following it have finished. A wait() helper stands in for a slow request here:

const wait = (ms, value) =>
new Promise((resolve) => setTimeout(resolve, ms, value));
console.log('loop starts');
for (let i = 1; i <= 3; i++) {
const pending = wait(100, `result ${i}`);
pending.then((value) => console.log(value));
console.log(`requested ${i}`, pending);
}
console.log('loop ends');

This prints:

loop starts
requested 1 Promise { <pending> }
requested 2 Promise { <pending> }
requested 3 Promise { <pending> }
loop ends
result 1
result 2
result 3

All three requests start at once, which is often what you want. To handle them one at a time instead, use await inside the loop, in an async function or a module:

const wait = (ms, value) =>
new Promise((resolve) => setTimeout(resolve, ms, value));
console.log('loop starts');
for (let i = 1; i <= 3; i++) {
const value = await wait(100, `result ${i}`);
console.log(value);
}
console.log('loop ends');

This prints:

loop starts
result 1
result 2
result 3
loop ends

await works in for, for...of and while loops. It does not work as intended inside a forEach() callback, because forEach() does not wait for the promise the callback returns.

Recursion is useful when each asynchronous step decides whether there is another, as when reading a paged API until a page comes back empty. The function calls itself from inside then(), after the previous result has arrived:

const wait = (ms, value) =>
new Promise((resolve) => setTimeout(resolve, ms, value));
function fetchPage(page) {
return wait(50, page < 3 ? [`item ${page}a`, `item ${page}b`] : []);
}
function collect(page, results) {
return fetchPage(page).then((items) => {
if (items.length === 0) {
return results;
}
return collect(page + 1, [...results, ...items]);
});
}
collect(1, []).then((all) => console.log(all));
console.log('collecting...');

This prints:

collecting...
[ 'item 1a', 'item 1b', 'item 2a', 'item 2b' ]

Each call returns before the next one starts, so this kind of recursion does not grow the call stack. A while loop with await does the same job and is usually easier to read. Async and await covers that style.

Steve Griffith covers this topic in his video Looping and Recursion in JavaScript.