Loading video player…

Run Loops Inside Loops

In this lesson, you started the Riverside Book Club’s year-end report with one member, Maya. You printed a star line for each of her books and a “which did you prefer?” question for every pair of them, by putting one loop inside another.

Key Points

  • Maya’s record holds her name and a list of books, and each book is a record with a title, an author, a genre and a rating from 0 to 5. Two of her books also have a review, which this lesson doesn’t use. Reading that shape first tells you what each loop goes through.
  • When you put a loop inside another loop, the inner loop runs all of its passes for each single pass of the outer loop. The two loops don’t take turns, one step each.
  • The inner loop’s end can come from the outer loop’s current item. In the star chart, the inner loop runs as many times as the book’s rating, so its body runs 5 + 4 + 3 + 4 = 16 times for Maya’s four books.
  • Anything that happens once per outer pass goes in the outer body, outside the inner loop. Create the row’s string at the top of the outer body, so each book starts with no stars, and log the line after the inner loop has finished.
  • If you create the string above both loops instead, it never starts over, and the stars pile up from book to book: The Martian shows nine stars and Educated shows sixteen.
  • To visit every pair once, start the inner loop at the position right after the outer one (j = i + 1). That skips a book paired with itself and every pair an earlier pass already asked. Maya’s four books give six questions: three, then two, then one, then none.

Final Code

The first script, chart.js, holds Maya’s record and prints her star chart:

Language: JavaScript Filename: chart.js
const maya = {
  name: "Maya",
  books: [
    {
      title: "Kindred",
      author: "Octavia E. Butler",
      genre: "sci-fi",
      rating: 5,
      review: "Couldn't put it down.",
    },
    { title: "The Martian", author: "Andy Weir", genre: "sci-fi", rating: 4 },
    {
      title: "Circe",
      author: "Madeline Miller",
      genre: "fantasy",
      rating: 3,
      review: "Slow start, lovely ending.",
    },
    { title: "Educated", author: "Tara Westover", genre: "memoir", rating: 4 },
  ],
};

for (const book of maya.books) {
  let stars = "";
  for (let i = 1; i <= book.rating; i++) {
    stars += "*";
  }
  console.log(`${book.title}: ${stars}`);
}

Run it, and Node prints one line per book:

Language: Shell
$ node chart.js
Kindred: *****
The Martian: ****
Circe: ***
Educated: ****

The second script, pairs.js, starts with the same maya record and prints a question for every pair of her books:

Language: JavaScript Filename: pairs.js
const maya = {
  name: "Maya",
  books: [
    {
      title: "Kindred",
      author: "Octavia E. Butler",
      genre: "sci-fi",
      rating: 5,
      review: "Couldn't put it down.",
    },
    { title: "The Martian", author: "Andy Weir", genre: "sci-fi", rating: 4 },
    {
      title: "Circe",
      author: "Madeline Miller",
      genre: "fantasy",
      rating: 3,
      review: "Slow start, lovely ending.",
    },
    { title: "Educated", author: "Tara Westover", genre: "memoir", rating: 4 },
  ],
};

for (let i = 0; i < maya.books.length; i++) {
  for (let j = i + 1; j < maya.books.length; j++) {
    console.log(`${maya.books[i].title} or ${maya.books[j].title}?`);
  }
}

Run it, and Node prints the six questions:

Language: Shell
$ node pairs.js
Kindred or The Martian?
Kindred or Circe?
Kindred or Educated?
The Martian or Circe?
The Martian or Educated?
Circe or Educated?

Next, in Loop Over an Object’s Keys and Values, you’ll loop over an object’s properties instead of an array’s elements.

00:00 In this course, you’re helping the Riverside Book Club turn a year of reading into a year-end report. The club’s log has lists inside records, so you’ll read each shape before you write a loop.

00:11 You’ll start small, with one member, Maya. Here’s her record. It has her name and a list of books. Each book is a record too, with a title, an author, a genre and a rating from zero to five.

00:25 Two of them also have a review.

00:28 Maya wants a star chart of her ratings for the year-end meeting, with each title followed by one star per point. For her first book, Kindred, you already know how.

00:38 Start with an empty string. A loop adds one star on each pass, and it runs once for each point of the rating. Then log the title and the stars. Run it, and Kindred gets five stars.

00:51 That’s one book, but Maya has four. Rather than copy this loop four times, you want it to run again for each book.

01:02 So you put it inside another loop. The outer loop goes through Maya’s books, one book per pass. The inner loop is the one you already wrote. The book now comes from the outer loop, so the inner loop runs as many times as that book’s rating.

01:18 Watch the passes. The outer loop picks up Kindred. The inner loop runs five times and builds five stars. When it’s finished, the outer body logs the line. Then the outer loop moves on to The Martian, and the inner loop starts again from one, this time for four passes.

01:37 By the end, there are four lines, one per book. The inner body ran five, plus four, plus three, plus four times: sixteen in all. Watch out: the two loops don’t take turns, one step each.

01:53 The inner loop finishes all its passes before the outer loop takes its next step, like a digital clock, where the minutes count all the way up to fifty-nine before the hour changes.

02:02 Unlike a clock, this inner loop doesn’t always count the same number of times.

02:09 Notice that the empty string sits at the top of the outer body. That’s the place for anything that happens once per book. Each new book starts with no stars.

02:19 Watch out: if you create that string above both loops instead, it never starts over. The stars keep piling up, so The Martian shows nine and Educated shows sixteen.

02:31 The line that prints sits in the outer body too, after the inner loop has finished, so each book gets one finished line.

02:41 Maya has a second idea. For the meeting, she wants a “which did you prefer?” question for every pair of her books. She wants each pair once, and never a book against itself.

02:52 This time, in a new script, both loops count positions, because the inner loop has to know where to start. The outer loop picks one book. The inner loop starts at the position right after it.

03:05 Each inner pass logs one question with the two titles. Starting there skips the book itself. And when the outer loop reaches The Martian, it’s already been paired with Kindred, so its inner loop starts at Circe.

03:20 Your turn: pause the video and predict how many questions this logs.

03:30 It logs six. Kindred meets three books. The Martian meets two. Circe meets one. Educated has no book after it, so its inner loop runs zero times.

03:43 Here’s the rule: the inner loop runs all of its passes for every single pass of the outer loop. Anything that happens once per outer pass goes in the outer body, outside the inner loop.

03:56 Four books is a toy chart, but the pattern works for any list. Next, in Loop Over an Object’s Keys and Values, you’ll loop over an object’s properties instead of an array’s elements.

Become a Member to join the conversation.