Loading video player…

Trace a Recursive Round Total

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 calls roundTotal() 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 category and its own total. While the Eighties call counts, Music’s call waits on that line, and its total stays at 2. 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 if makes that stop plain to see.
  • Each call returns its answer to the call that made it, and the caller adds it in with +=. The 4 from Eighties reaches Music’s total only because of that +=. On a line of its own, the call would still return 4, and the 4 would 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. The at lines below it name roundTotal over and over.

The Final Code

Here’s the sheet and the function that totals it, saved as round-total.js:

Language: JavaScript Filename: 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:

Language: Shell
$ 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.

00:00 Last time, Marco’s scoring helpers each called the next. This time, a function calls itself, and you’ll trace every call. It’s Round 4 at the Lantern, and the round is Music.

00:13 Marco marks each team’s sheet by category. Here’s The Quizzards’ sheet. Music is worth 2 points and holds two smaller categories. Eighties is worth 3 and holds a single category, Synth-pop, which is worth 1.

00:27 Movie Themes is worth 2, and its list of categories is empty.

00:32 Marco wants one number for the round. But categories can hold categories, and those can hold more. One loop over Music’s list would never reach Synth-pop, a level further down.

00:45 Here’s a function that totals any category. It takes one category and returns a number.

00:51 First, the if statement checks for a category with nothing inside. That category returns its own points, and the call is done. Otherwise, total starts at the category’s own points.

01:04 Then the loop goes through each smaller category and adds its round total. Look at the line inside the loop: roundTotal() calls itself. A function that calls itself is recursive, and the idea is called recursion.

01:18 So every smaller category gets its own call, all the way down to Synth-pop.

01:25 The top level of the script sits at the bottom of the stack. It calls roundTotal() with Music, and a frame goes on top. Its total starts at 2.

01:35 The loop reaches Eighties and calls roundTotal() again. A second frame of the same function lands on top. Its total starts at 3. Watch out: these are two different totals.

01:48 The new call has its own total, so Music’s total stays at 2 while it waits. Eighties holds Synth-pop, so a third frame goes on. Synth-pop holds nothing, so its call returns 1 at once.

02:02 This is called the base case, a category the function answers without calling itself again.

02:09 The Synth-pop frame comes off the stack, and its 1 travels down to Eighties. Your turn: pause the video and predict what the Eighties call hands back to Music.

02:24 Eighties has nothing left to visit, so it returns 4: its own 3, plus the 1 from Synth-pop. That frame comes off, and Music’s total goes from 2 to 6. Note that the 4 only reaches Music’s total because += adds it in.

02:41 On a line of its own, the call’s 4 would come back and be thrown away.

02:46 Next, the loop reaches Movie Themes. Its frame goes on, returns 2, and comes off. Music’s total goes up to 8. Music’s loop is done, so its frame comes off, and its 8 goes back to the top level.

03:01 Run the program, and the top level prints 8.

03:06 Every chain of calls has to reach a base case. Say the call inside the loop passed Music’s own category again instead of the smaller one. Every call gets Music again, so none reaches the base case, and the frames pile up.

03:22 Run it, and a RangeError stops the program. The maximum call stack size was exceeded. Below it, the “at” lines name roundTotal() over and over.

03:33 Pass the smaller category instead, and each call gets one step closer to an empty list. So, to trace a recursive call, follow the frames. Each call has its own frame and its own total.

03:47 Each one returns its answer to the call that made it, and the caller adds it in.

03:53 That’s all you need about recursion for now. You’ll meet this round total again in Marco’s finished kit. Next comes Exercise: Trace Marco’s Scoring Calls, the course’s first coding exercise.

04:06 You write and run code right in your browser, and automated tests tell you how it’s going. You’ll get Marco’s answer-scoring helpers ready for quiz night, with no recursion to write.

Become a Member to join the conversation.