Nested Loop
Learn how to use JavaScript nested loops to iterate through multi-dimensional data and complex grids.
What is a Nested Loop?Link to this section
A nested loop is a loop placed inside the body of another loop. The inner loop executes all its iterations for every single iteration of the outer loop.
This example shows the inner loop completing both cycles while the outer loop stays on 1, then repeating when the outer loop moves to 2.
- `for (let i = 1; i <= 2; i++)` is the **outer loop**.
- `for (let j = 1; j <= 2; j++)` is the **inner loop**.
- `console.log(...)` is the **inner block** that runs repeatedly.
Nested loops are used whenever you need to process two-dimensional data structures like grids, tables, or coordinate systems.
Why Do We Need Nested Loops?Link to this section
Nested loops are essential when single loops cannot reach every element in multi-layered or grid-based data structures.
- Process rows and columns in a seating chart or theater grid.
- Generate a multiplication table for school homework.
- Loop through pixels on a 2D digital image canvas.
- Compare every item in one list against every item in another list.
- Print patterns like triangles or squares made of asterisks.
- Manage multi-level category data in an e-commerce catalog.
This prints out every individual seat location in a small 3x2 room.
Without nested loops, you would have to write repetitive manual logging statements for every single row and column combination.
About Nested LoopsLink to this section
Nested loops can combine any loop types together, such as a for loop inside a while loop. The total number of executions for the innermost code equals the outer loop count multiplied by the inner loop count. Performance can drop quickly with deep nesting, so you should avoid nesting loops more than three levels deep unless necessary.
| Outer Loop Type | Inner Loop Type | Use Case |
|---|---|---|
| for | for | Grids, matrices, and multiplication tables |
| while | for | Condition-based external state with fixed inner counts |
| for | while | Fixed row iteration with dynamic inner search conditions |
Mixing a while loop as the outer loop and a for loop as the inner loop.
Types and Variations of Nested LoopsLink to this section
1. Nested For LoopsLink to this section
The most common form of nesting, where a for loop sits inside another for loop. It is ideal when you know the exact number of iterations needed for both levels.
Prints the product values for a basic grid calculation.
Calculates multiple tax rates applied to multiple base prices.
tip
warning
2. Nested While LoopsLink to this section
Placing a while loop inside another while loop allows you to repeat actions based on changing conditions at multiple levels.
Both loops rely on manual increment steps to eventually terminate.
warning
3. Nested Loops with ArraysLink to this section
Nested loops are heavily used to iterate over two-dimensional arrays, which are arrays containing other arrays as their elements.
Iterates through every row and every column cell in a 2D matrix.
note
4. Control Statements in Nested LoopsLink to this section
Using break or continue inside a nested loop only affects the loop it is directly written inside, unless label statements are used.
The break statement only stops the inner loop when j reaches 2, leaving the outer loop running.
tip
Performance and Time ComplexityLink to this section
Nested loops multiply the total number of operations performed. If an outer loop runs N times and an inner loop runs M times, the code inside runs N times M times.
A 100 by 100 loop runs ten thousand times.
warning
Labeled StatementsLink to this section
Labels let you target an outer loop specifically from inside an inner loop when using break or continue.
Stops both loops entirely the moment the condition is met.
note
Complete Coding ExampleLink to this section
Calculates and prints the average score for each student across multiple test grades.
The outer loop moves through each student row, while the inner loop adds up their individual test scores.
Important NotesLink to this section
- A nested loop consists of an outer loop and one or more inner loops.
- The inner loop completes all its cycles for every single cycle of the outer loop.
- Always use distinct counter variable names like i and j for nested loops.
- The total number of inner executions equals outer count multiplied by inner count.
- A break or continue statement inside an inner loop only affects that inner loop.
- Matrix and 2D array traversals are the most common use cases for nested loops.
- Deeply nested loops can cause slow performance on large datasets.
- Labeled breaks allow you to exit an outer loop from inside an inner loop.
- Forgetting to reset an inner while loop counter can cause infinite loop bugs.
- Nested loops can combine different loop types such as a for loop inside a while loop.
SummaryLink to this section
Nested loops allow developers to execute repetitive tasks within repetitive tasks, making them indispensable for handling multi-dimensional data structures like grids and tables. By carefully managing counter variables and performance considerations, you can solve complex iteration challenges efficiently. This mastery prepares you for working with advanced data structures and algorithms in future lessons.
Check Your UnderstandingLink to this section
What happens when you use a break statement inside an inner loop?
Practice ChallengesLink to this section
1. Coordinate Grid Printer
Write a nested loop that prints coordinate pairs from (1,1) up to (2,2). Use console.log to print each pair in the format x: 1, y: 1.
Expected output
x: 1, y: 1
x: 1, y: 2
x: 2, y: 1
x: 2, y: 2Hint: Use two for loops with counters x and y running from 1 to 2.
2. Multiplication Table Row
Create a nested loop where the outer loop runs from 1 to 2 and the inner loop runs from 1 to 3, printing the product of the two loop counters.
Expected output
1
2
3
2
4
6Hint: Multiply outer variable i by inner variable j inside the inner loop block.
3. 2D Matrix Sum Calculator
Given a 2D array of numbers [[1, 2], [3, 4]], use nested loops to calculate and print the total sum of all numbers combined.
Expected output
10Hint: Declare a sum variable outside both loops and add each matrix element to it inside the inner loop.
4. Asterisk Triangle Pattern
Write a nested loop that prints a triangle pattern of asterisks with 3 rows, where row 1 has one asterisk, row 2 has two, and row 3 has three.
Expected output
*
**
***Hint: Make the inner loop condition depend on the outer loop counter value, such as j <= i.
5. Inventory Batch Price Combiner
You have two arrays of base prices [100, 200] and discount multipliers [0.9, 0.8]. Use nested loops to calculate and print every combination of discounted price rounded to whole numbers.
Expected output
90
80
180
160Hint: Multiply each item in the prices array by each item in the multipliers array.
Rate this content
Sign in to rate
Discussion
Sign in to join the discussion