In this lesson, you traced a function that calls itself as it totals The Quizzards’ answer sheet for Round 4 at the Lantern. Music holds Eighties, which holds Synth-pop, and Music also holds Movie Themes.
Key Points
- A function that calls itself is recursive, and the idea is called recursion. In
roundTotal(), the line inside the loop callsroundTotal()again for each smaller category, so the function reaches every level, however deep it sits. - Every call gets its own frame on the call stack, with its own
categoryand its owntotal. While the Eighties call counts, Music’s call waits on that line, and itstotalstays at2. Under them all sits the top level of the script. - A category with nothing inside returns its own points without calling the function again. That’s the base case. The loop would visit nothing there anyway, and the
ifmakes that stop plain to see. - Each call returns its answer to the call that made it, and the caller adds it in with
+=. The4from Eighties reaches Music’stotalonly because of that+=. On a line of its own, the call would still return4, and the4would be thrown away. - Each call needs a smaller category, one step closer to an empty list. If the calls never reach the base case, the frames pile up until Node stops with
RangeError: Maximum call stack size exceeded. Theatlines below it nameroundTotalover and over.
The Final Code
Here’s the sheet and the function that totals it, saved as round-total.js:
round-total.js
const sheet = {
name: "Music",
points: 2,
categories: [
{
name: "Eighties",
points: 3,
categories: [
{ name: "Synth-pop", points: 1, categories: [] },
],
},
{ name: "Movie Themes", points: 2, categories: [] },
],
};
function roundTotal(category) {
if (category.categories.length === 0) {
return category.points;
}
let total = category.points;
for (const sub of category.categories) {
total += roundTotal(sub);
}
return total;
}
console.log(roundTotal(sheet));
Run it with node, and it prints the round’s total:
$ node round-total.js
8
Synth-pop’s call returns 1, so Eighties returns 4. Movie Themes returns 2, so Music ends on 2 + 4 + 2, which is 8. Music’s call returns that 8 to the top level, and console.log() prints it.
Next comes Exercise: Trace Marco’s Scoring Calls, where you’ll get Marco’s answer-scoring helpers ready for quiz night.