Sometimes it can be necessary to use a loop inside another loop. A loop inside a loop is called a nested loop.
Warning: Often, nesting loops is not the best solution to a problem. It can sometimes be a sign of poorly written code (often called a "code smell" among programmers) because it can make your code run slower. However, every now and then, it is a perfectly fine and necessary solution to a problem.
Here is what nesting would look like for while loops:
while (condition 1) {
// code that gets executed as long as condition 1 is true
// this outer loop depends on condition 1 being true
while (condition 2) {
// code that gets executed as long as condition 2 is true
// this inner loop runs completely for EVERY iteration of the outer loop
}
}
Nesting can also be used with for loops, or with a combination of both for and while loops. They can even go several levels deep!
A common example of when we might use nested loops is when we want to create an array of arrays (a 2D array).
With the outer loop, we create the top-level array, and with the inner loop, we add the values into those sub-arrays.
let arrOfArrays = [];
for (let i = 0; i < 3; i++) {
arrOfArrays.push([]); // Create a new array for this row
for (let j = 0; j < 7; j++) {
arrOfArrays[i].push(j); // Add values 0-6 to the current row
}
}
console.log(arrOfArrays);
When we log this array using console.log(arrOfArrays);, we can see that the output is an array containing three arrays, each with values from 0 up to 6
console.table()We used nested loops to create an array inside an array, meaning we can work with rows and columns. This means nested loops are perfect for creating tabular data.
We can actually visualize this output as a table in the browser developer tools using the console.table() method instead of console.log():
console.table(arrOfArrays);
This will output a neatly formatted table in the console:
┌─────────┬───┬───┬───┬───┬───┬───┬───┐
│ (index) │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │
├─────────┼───┼───┼───┼───┼───┼───┼───┤
│ 0 │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │
│ 1 │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │
│ 2 │ 0 │ 1 │ 2 │ 3 │ 4 │ 5 │ 6 │
└─────────┴───┴───┴───┴───┴───┴───┴───┘
If an outer loop runs 3 times, and its inner loop runs 5 times per iteration, how many times does the inner loop's code execute in total?