Nested Loops
In this lesson, we will look at nested loops in JavaScript. A nested loop is a loop inside another loop. It is often used when working with multiple arrays or with nested arrays.
Example: We want to print all possible pairs of numbers from two lists:
const numbers1 = [1, 2];
const numbers2 = [3, 4];
for (const number1 of numbers1) {
for (const number2 of numbers2) {
console.log(number1 + " " + number2);
}
}
Output:
1 3
1 4
2 3
2 4
In this example, we iterate through all numbers in the list numbers1
and for each number in this list, we iterate through all numbers in the list numbers2
. For each combination of numbers, we print the pair.
Instructions
Using a for
loop, iterate through cities
, and using a nested for
loop, iterate through activities
and print each pair of values.
Insert a space between each pair.
Start programming for free
8/9