Choose Items or Positions

You can now look at a list in two ways. A for...of loop hands you every item in order, and an index like playlist[2] reaches one item by its position. Most real tasks need you to go through the whole list, and that’s where the two ideas meet. Sometimes you only care about each item, and sometimes you also need to know where it sits.

In this lesson, you’ll trace both kinds of loop pass by pass, see which tasks need positions, and write a small function that picks the right loop for its job. Keep a pen and paper close, because most examples ask you to predict a result before you run it.

Walk Through the Items With for...of

Back on the train ride, you’d like to know how long your playlist plays. Say the four songs last 4, 3, 5, and 6 minutes. To get the total, you need every length, but you never need to know which position a length came from. That’s a job for for...of.

Language: JavaScript
function totalMinutes(lengths) {
  let total = 0;
  for (const length of lengths) {
    total = total + length;
  }
  return total;
}

console.log(totalMinutes([4, 3, 5, 6]));
console.log(totalMinutes([]));
Language: Program Output
18
0

The variable total is a running total. It starts at 0 before the loop, because when playback begins, you’ve listened for zero minutes. Each pass adds one length to it, and after the loop, the function returns whatever total has reached. Here’s the same run, one pass at a time.

Pass length total after the pass
1 4 4
2 3 7
3 5 12
4 6 18

The empty list gets zero passes, just like the empty bag in the video, so total never moves from 0. Notice that the table has no column for positions. The loop doesn’t give you a position, and the job doesn’t need one.

Number the Songs With a Counting Loop

Now you’d like to print the playlist with track numbers, as in 1. Rainy Day Waltz. A for...of loop gives you each song, but not its place in the list. For that, you can use the counting for loop you know from earlier courses and let its counter walk through the indices.

Language: JavaScript
const playlist = [
  "Rainy Day Waltz",
  "Sunny Side Up",
  "Mountain Echo",
  "Last Train Home"
];

for (let i = 0; i < playlist.length; i++) {
  console.log((i + 1) + ". " + playlist[i]);
}
Language: Program Output
1. Rainy Day Waltz
2. Sunny Side Up
3. Mountain Echo
4. Last Train Home

Locked learning resources

Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Locked learning resources

The full lesson is for members only. Join us and get access to thousands of tutorials and a community of expert JavaScript developers.

Unlock This Lesson

Already a member? Sign-In

Become a Member to join the conversation.