Grid Iteration
Nested loops are perfect for 2D grids like tables, boards, and matrices.
The outer loop controls rows and the inner loop controls columns.
JavaScript Tutorial
Nested loops place one loop inside another to handle multi-dimensional data.
They are common in grid processing, pattern printing, and pair comparisons.
Some tasks require comparing every item to every other item or iterating 2D structures.
Knowing nested loops helps you handle those cases while being mindful of performance.
for (...) {
for (...) { ... }
}const grid = [
[1, 2],
[3, 4],
];
for (let r = 0; r < grid.length; r++) {
for (let c = 0; c < grid[r].length; c++) {
console.log(grid[r][c]);
}
}Nested loops iterate rows and columns.
const items = ["a", "b", "c"];
for (let i = 0; i < items.length; i++) {
for (let j = i + 1; j < items.length; j++) {
console.log(items[i], items[j]);
}
}Generate unique pairs with a nested loop.
Nested loops are perfect for 2D grids like tables, boards, and matrices.
The outer loop controls rows and the inner loop controls columns.
Use nested loops to compare each item with others or generate pairs.
Be mindful of performance as the work grows quickly (O(n^2)).
Nested loops can be expensive for large datasets.
Consider breaking early with break or using smarter algorithms.
let found = false;
for (let i = 0; i < 3 && !found; i++) {
for (let j = 0; j < 3; j++) {
if (i + j === 4) {
found = true;
break;
}
}
}
console.log(found);Use a flag to break out of nested loops.
let pattern = "";
for (let i = 0; i < 3; i++) {
for (let j = 0; j <= i; j++) {
pattern += "*";
}
pattern += "
";
}
console.log(pattern);Nested loops are common in pattern generation.
Without
for (let i = 0; i < rows; i++) {
// no inner loop
}With
for (let r = 0; r < rows; r++) {
for (let c = 0; c < cols; c++) {
// process grid cell
}
}Consider algorithmic alternatives for large data sets.
Break only exits the inner loop unless you use a flag.
Use descriptive names like row and col for readability.
Often O(n^2), depending on bounds.
Use a flag, labeled break, or return from a function.
For grids, combinations, and pairwise comparisons.
Practice: Use nested loops to print a 3x3 multiplication table.
// TODO: print 1..3 multiplied by 1..3
One Possible Solution
for (let i = 1; i <= 3; i++) {
for (let j = 1; j <= 3; j++) {
console.log(i * j);
}
}They often scale with O(n^2) or worse as data grows.
Use a flag, labeled break, or return from a function.
For grids, combinations, and comparisons across pairs.
Try different grid sizes to see how nested loops behave.