Nested Loops

A loop can contain another loop. This is called a nested loop. In each iteration of the outer loop, the inner loop runs all the way through. Let's list every T-shirt a shop sells, in every size and every color:

const sizes = ["S", "M"];
const colors = ["red", "blue", "black"];
for (const size of sizes) {
    for (const color of colors) {
        console.log(size, color);
    }
}
S red
S blue
S black
M red
M blue
M black

The outer loop takes "S", and the inner loop goes through all three colors. Only then does the outer loop take "M", and the inner loop goes through all the colors again. The inner block runs 2 × 3 = 6 times. Give the variables of the two loops different names (here size and color), so that you know which is which.

Nested loops are also how you go through nested arrays. The outer loop takes one inner array at a time, and the inner loop goes through its elements:

const groups = [["Anna", "Tom"], ["Eva", "Peter", "Jack"]];
for (const group of groups) {
    console.log("Group:", group);
    for (const name of group) {
        console.log("Hello,", name);
    }
}
Group: ["Anna", "Tom"]
Hello, Anna
Hello, Tom
Group: ["Eva", "Peter", "Jack"]
Hello, Eva
Hello, Peter
Hello, Jack

Instructions

A travel agency offers a trip to each city in cities with each activity in activities. Write a loop over cities and, nested inside it, a loop over activities, and print every pair with console.log(city, activity);. The output starts with Prague Tennis, Prague Shopping, Prague Sightseeing, Brno Tennis…

Count the trips: before the loops, create a variable count with the value 0, increase it by one in the inner loop, and after both loops, print console.log("Number of trips:", count);. The output is Number of trips: 12.

Start programming for free

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

Or sign up with:

Back

11/12

Next