3.9 Nested Loops and Grid Thinking
A nested loop is a loop inside another loop. It is useful whenever your data has two dimensions: rows and columns, calendars, pixel grids, seating charts, tables, and game boards.
The important idea is simple: every time the outer loop runs once, the inner loop usually runs all the way through.
Rows and columns
This code prints a 3 by 4 grid of coordinates:
for (let row = 1; row <= 3; row++) {
for (let col = 1; col <= 4; col++) {
console.log(`row ${row}, col ${col}`);
}
}The outer loop controls rows. The inner loop controls columns within the current row.
Building text one row at a time
When printing or generating a pattern, build each row inside the outer loop:
for (let row = 1; row <= 4; row++) {
let line = "";
for (let col = 1; col <= row; col++) {
line += "*";
}
console.log(line);
}Output:
*
**
***
****This mirrors the Python nested-loop idea, but the JavaScript version often builds a string first and then prints or inserts it into the page.
Creating a small table with JS
Nested loops can also generate HTML:
let html = "<table>";
for (let row = 1; row <= 3; row++) {
html += "<tr>";
for (let col = 1; col <= 3; col++) {
html += `<td>${row},${col}</td>`;
}
html += "</tr>";
}
html += "</table>";
document.querySelector("#grid").innerHTML = html;This is not always the final production style, but it shows why nested loops are powerful: one loop chooses the row, the other fills the cells.
Keep nested loops readable
Use names like row, col, i, and j carefully. When the loops represent a real concept, name the variables after that concept:
for (let week = 1; week <= 4; week++) {
for (let day = 1; day <= 7; day++) {
console.log(`week ${week}, day ${day}`);
}
}