A cinema has 3 rows of 4 seats. How would a program label every seat A1 to C4 without 12 separate lines?
Keep the question in mind. By the end of the lesson you will be able to answer it, and prove it with working code.
02Start with working code
The inner loop runs completely for every pass of the outer loop.
const rows = ["A", "B"];
for (const row of rows) {
let line = "";
for (let seat = 1; seat <= 3; seat++) {
line += row + seat + " ";
}
console.log(line.trim());
}
03Objective and prerequisites
Learning objective: Write nested loops, predict how many times the inner body runs, build text patterns and grids, and recognise when nesting becomes slow.
A nested loop is a loop inside another loop. For every iteration of the outer loop, the inner loop runs from start to finish.
If the outer loop runs 3 times and the inner loop runs 4 times, the inner body runs 3 × 4 = 12 times.
Use different counter names (row and col, or i and j) so you can tell the loops apart.
Build each row as a string in the outer loop, add to it in the inner loop, and print it after the inner loop ends. This is how grids and star patterns are made.
Nested loops over the same data are O(n²): 1,000 items means 1,000,000 inner iterations. For lookups, a Set or Map built once usually replaces the inner loop.
An inner loop that starts at the outer index (for (let j = i + 1; ...)) visits each pair once, halving the work for pair comparisons and avoiding comparing an item with itself.
Deep nesting hurts readability. Extract the inner loop into a well-named function such as buildRow(row) once a pattern is understood.
Two-dimensional data is commonly stored as arrays of arrays: grid[row][col]. Keep the row/column order consistent across your code.
05Definitions
Nested loop
A loop placed inside the body of another loop.
Outer loop
The loop that contains another loop.
Inner loop
The loop inside; it runs fully for each outer iteration.
Grid (2D array)
An array of arrays, read with grid[row][col].
Quadratic time
Work that grows with the square of the input size, typical of nested loops over the same list.
The outer loop picks the row; the inner loop picks the seat number.
const rows = ["A", "B", "C"];
for (const row of rows) {
let line = "";
for (let n = 1; n <= 4; n++) {
line += `${row}${n} `;
}
console.log(line.trim());
}
Sample input
None
Expected output
A1 A2 A3 A4
B1 B2 B3 B4
C1 C2 C3 C4
Common mistake
Printing inside the inner loop, which gives one seat per line.
A booking page draws a seat map from a number of rows and seats per row. Nested loops produce every label, and changing the hall size needs no new code.
for (const r of ["A", "B"]) {
const seats = [];
for (let n = 1; n <= 3; n++) seats.push(r + n);
console.log(seats.join(" "));
}
12Knowledge check
1. How many times does the inner body run?
for (let i = 0; i < 4; i++) {
for (let j = 0; j < 3; j++) {
// body
}
}
7
12
4
3
2. When does the inner loop restart from its first value?
Never
On every outer iteration
Only once
When break runs
3. What is the last line?
for (let r = 1; r <= 3; r++) console.log("*".repeat(r));
***
**
*
****
4. Why is each row's total too high?
let rowTotal = 0;
for (const row of grid) {
for (const v of row) rowTotal += v;
console.log(rowTotal);
}
rowTotal is declared outside the outer loop
The inner loop is wrong
+= cannot add numbers
The grid is empty
5. Why start the inner loop at j = i + 1 when comparing pairs?
It is faster and avoids self- and duplicate pairs
It is required syntax
It sorts the data
It prevents errors
6. Checking 10,000 emails against 10,000 others: which scales better?
Nested loops
Build a Set once, then one loop
They are equal
Neither works
13Solutions and tests
Each exercise's solution appears in the exercise once you have run its tests. Solutions are one possible answer: the tests accept any implementation with the same behaviour.
Automated acceptance tests for this lesson
These are the same checks the exercises run. They are visible on purpose: client-side tests help you learn and are not secret.
Rows, not a column: Two rows
Multiplication grid: Prints the grid; Uses nested loops
Find matching pairs: Prints both pairs; pairs is 2; Inner loop starts after i
ex-019-01: output matches the documented expected output
ex-019-02: output matches the documented expected output
ex-019-03: output matches the documented expected output
ex-019-04: output matches the documented expected output
The lesson lives in the companion repository at curriculum/level-01-foundations/module-04-repetition-and-problem-solving/lesson-019-nested-loops-and-patterns/. Every example on this page is generated from those files.
These links open the files in the GitHub repository (https://github.com/lsvekis/JavaScript-Professional-Engineering-Academy). You can also use the ZIP download above.
15Summary and next steps
The inner loop runs fully for each outer iteration.
Total inner runs = outer × inner.
Build a row in the outer loop, print it after the inner loop.
Nested loops over the same data grow quadratically.
Copy a prompt into the AI assistant of your choice. Then verify what it says by running code here. No AI service is connected to this page.
Concept explanationNested loops
Context: I know single loops.
Task: Explain nested loops with a seat map and a trace table of both counters.
Constraints: Beginner level.
Expected behaviour: I can predict how many times the inner body runs.
Testing: Ask me three counting questions.
Code predictionPattern drill
Context: I understand nested loops.
Task: Show me five pattern programs and ask what each prints.
Constraints: Wait for answers.
Expected behaviour: Include triangles and grids.
Testing: Explain the inner limit each time.
DebuggingPattern looks wrong
Context: My triangle prints as a rectangle.
Task: Help me find why with questions about the inner limit.
Constraints: No direct answer.
Expected behaviour: I fix it myself.
Testing: Suggest logging both counters.
Exercise generationGrid problems
Context: I finished the multiplication grid.
Task: Create three grid exercises with arrays of arrays.
Constraints: Fictional data, exact output.
Expected behaviour: Include row and column totals.
Testing: Include expected output.
Code reviewSlow nested loops
Context: My code compares two lists with nested loops.
Task: Show me a faster approach and explain why.
Constraints: Keep the result identical.
Expected behaviour: Explain the number of operations before and after.
Testing: Compare readability.