Nested Loops
Loops inside loops. Process grids, matrices, and multi-dimensional data.
How Nested Loops Work
The inner loop completes all its iterations for each single iteration of the outer loop.
// Outer loop runs 3 times
for (let i = 0; i < 3; i++) {
// Inner loop runs 3 times FOR EACH outer iteration
for (let j = 0; j < 3; j++) {
console.log(i, j);
}
}
// Total: 3 Ć 3 = 9 pairsš Think of it like a clock:
Outer loop (i) = hours hand ā moves slowly
Inner loop (j) = minutes hand ā completes full rotation for each hour
For each step of the outer loop, the inner loop runs completely from start to finish.
i=0: j=0, j=1, j=2 (inner completes) i=1: j=0, j=1, j=2 (inner completes again) i=2: j=0, j=1, j=2 (inner completes again)
The outer loop advances only after the inner loop finishes all its iterations.
Grid Visualization
Watch nested loops fill a grid cell by cell.
for (let row = 0; row < 4; row++) {
for (let col = 0; col < 4; col++) {
// Process cell at (row, col)
}
}row = 0, col = 0
Step 1 of 16
Iteration Counting
Total iterations = outer Ć inner.
Total iterations:
3Ć4=12
// 3 levels deep:
for (let i = 0; i < 3; i++) { // 3 times
for (let j = 0; j < 4; j++) { // Ć 4 times
// Total: 3 Ć 4 = 12 operations
}
}
// With 3 nested loops:
for (let i = 0; i < 10; i++) { // 10
for (let j = 0; j < 10; j++) { // Ć 10
for (let k = 0; k < 10; k++) { // Ć 10
// = 1,000 total operations!
}
}
}ā ļø Nested loops multiply. 3 loops of 100 = 100 Ć 100 Ć 100 = 1,000,000 operations. Be careful with deep nesting!
Common Patterns
Real-world uses of nested loops.
const matrix = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
];
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix[row].length; col++) {
console.log(matrix[row][col]);
}
}
// 1, 2, 3, 4, 5, 6, 7, 8, 9Performance Considerations
Nested loops can be expensive. Know when to avoid them.
| Loops | Complexity | n=1000 |
|---|---|---|
| 1 loop | O(n) | 1,000 |
| 2 nested | O(n²) | 1,000,000 |
| 3 nested | O(n³) | 1,000,000,000 |
ā When nested loops are fine:
- Small datasets (n < 100)
- Actual 2D data (matrices, grids, tables)
- Comparing all pairs (when there's no better algorithm)
ā When to avoid:
- Large datasets ā use a Set or Map for O(n) lookups instead
- Searching ā sort first, then binary search O(n log n)
- More than 3 levels deep ā refactor into functions
// ā O(n²) ā checking duplicates with nested loop
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (arr[i] === arr[j]) found = true;
}
}
// ā O(n) ā use a Set instead
const seen = new Set();
for (const item of arr) {
if (seen.has(item)) { found = true; break; }
seen.add(item);
}Frequently Asked Questions
Common questions about nested loops.