Beginner-Friendly Topic
Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!
Lesson 8 of 10
Nested Loops & Loop Patterns
Nested loops are loops inside loops - essential for working with 2D data (tables, matrices, grids), generating patterns, and comparing elements. The inner loop runs completely for each iteration of the outer loop.
Nested Loop Concepts
- Outer loop runs N times. Inner loop runs M times per outer iteration = N ร M total
- 2D arrays - Use nested loops to access rows and columns: matrix[row][col]
- Multiplication tables - Classic nested loop example: outer = row, inner = column
- Comparing elements - Nested loops compare every pair: for i, for j > i
- Performance - Nยฒ complexity. For large data, consider more efficient algorithms
Nested Loops Code
// Multiplication table (3x3)
for (let i = 1; i <= 3; i++) {
let row = "";
for (let j = 1; j <= 3; j++) {
row += `${i}x${j}=${i*j}\t`;
}
console.log(row);
}
// 2D array (matrix)
const grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
];
for (let row = 0; row < grid.length; row++) {
for (let col = 0; col < grid[row].length; col++) {
console.log(`grid[${row}][${col}] = ${grid[row][col]}`);
}
}
// Find duplicates in array
const nums = [1, 3, 5, 3, 7, 1];
for (let i = 0; i < nums.length; i++) {
for (let j = i + 1; j < nums.length; j++) {
if (nums[i] === nums[j]) {
console.log(`Duplicate: ${nums[i]} at index ${i} and ${j}`);
}
}
}Tip
Tip
Be mindful of nested loop performance - N ร M iterations can be slow for large datasets. A 1000ร1000 nested loop runs 1 million times. If possible, use Map/Set lookups (O(1)) instead of inner loops for searching.
map/filter return new arrays; sort/splice mutate the original
Common Mistake
Warning
Using nested loops to find duplicates in large arrays is O(nยฒ) - very slow. For production code, use a Set instead: const seen = new Set(); for (const item of arr) { if (seen.has(item)) { /* duplicate */ } seen.add(item); } - this is O(n).
Practice Task
Note
Practice nested loops: (1) Print a 5x5 multiplication table. (2) Create a triangle pattern of stars (1 star, then 2, then 3...). (3) Find all pairs in an array that sum to a target number.
Quick Quiz
Key Takeaways
- Nested loops are loops inside loops - essential for working with 2D data (tables, matrices, grids), generating patterns, and comparing elements.
- Outer loop runs N times. Inner loop runs M times per outer iteration = N ร M total
- 2D arrays - Use nested loops to access rows and columns: matrix[row][col]
- Multiplication tables - Classic nested loop example: outer = row, inner = column
Finished this lesson?