Looping Through Arrays

Loops and arrays belong together. With a for loop, you can go through the indexes of an array, from 0 to the last one, and read each element:

const games = ["Football", "Tennis", "Golf"];
for (let i = 0; i < games.length; i++) {
    console.log(games[i]);
}

This prints:

Football
Tennis
Golf

The counter i starts at 0, the first index. The condition i < games.length ends the loop after the last index, which is games.length - 1. A common mistake is i <= games.length: the loop then runs once more, reads games[3], which doesn't exist, and prints undefined. Thanks to .length, the loop works for an array of any length, even after you .push() more elements into it.

Going through all the elements is so common that JavaScript has a simpler loop for it, for...of:

const games = ["Football", "Tennis", "Golf"];
for (const game of games) {
    console.log(game);
}
Football
Tennis
Golf

Read it as “for each game of games”. In each iteration, the variable game holds the next element: first "Football", then "Tennis" and then "Golf". You don't need an index or .length at all. Name the variable after one element of the array: game of games, name of names.

Why can game be a const when the counter of a classic for must be a let? Because for...of creates a new game variable for each iteration, and nothing changes it during that iteration. The counter i is one variable that i++ keeps changing.

So which one should you use? for...of when you want each element, one after another. It is shorter, and you can't get the indexes wrong. The classic for when you also need the index, for example to number the elements, or when you want to go backwards or skip some of them.

Instructions

Write a for...of loop that prints each element of the teammates array on its own line.

Below it, write a classic for loop with an index that prints the teammates with their numbers: 1. Takashi, 2. Tom, 3. John and 4. Tory. The number is the index plus one.

Start programming for free

By signing up, you agree to the Terms of Service and Privacy Policy.

Or sign up with:

Back

4/12

Next