JavaScript AcademyProfessional Engineering
Level 1 · FoundationsModule 4: Repetition and Problem-SolvingLesson 19 of 150About 45 minutes

Lesson 19: Nested loops and patterns

01Opening question

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.

You need: Lesson 16: For loops, Lesson 18: Break and continue

Skills practised: Loops, Nested loops.

04Explanation

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.

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.

Open the full glossary

06Visual learning object

Nested-loop pattern builder. Choose rows, columns and a pattern and watch the outer and inner counters build it.

Loading the interactive object…

Open the full Nested-loop pattern builder page with its guided experiment.

07Examples

ex-019-01Labelling seats Browser-executable JavaScript

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.
Try this
Add a fourth row D.
Source
examples/ex-019-01-seat-labels.js

ex-019-02A star triangle Browser-executable JavaScript

The inner loop's length depends on the outer counter.

for (let row = 1; row <= 4; row++) {
  let stars = "";
  for (let s = 0; s < row; s++) {
    stars += "*";
  }
  console.log(stars);
}
Sample input
None
Expected output
* ** *** ****
Common mistake
Using a fixed inner limit, which prints a rectangle.
Try this
Turn the triangle upside down.
Source
examples/ex-019-02-triangle.js

ex-019-03Counting inner iterations Browser-executable JavaScript

The inner body runs outer × inner times.

let runs = 0;
for (let i = 0; i < 3; i++) {
  for (let j = 0; j < 5; j++) {
    runs++;
  }
}
console.log("Inner body ran", runs, "times");
Sample input
None
Expected output
Inner body ran 15 times
Common mistake
Adding the counts (3 + 5) instead of multiplying.
Try this
Predict the count for 10 by 10, then run it.
Source
examples/ex-019-03-count-iterations.js

ex-019-04Reading a grid Browser-executable JavaScript

grid[row][col] reaches each cell of an array of arrays.

const sales = [
  [5, 3, 0],
  [2, 8, 4]
];
for (let r = 0; r < sales.length; r++) {
  let rowTotal = 0;
  for (let c = 0; c < sales[r].length; c++) {
    rowTotal += sales[r][c];
  }
  console.log(`Store ${r + 1}: ${rowTotal}`);
}
Sample input
None
Expected output
Store 1: 8 Store 2: 14
Common mistake
Using sales.length for the inner loop, which counts rows instead of columns.
Try this
Also print the grand total of all stores.
Source
examples/ex-019-04-grid-sum.js

08Guided exercises

Three exercises: explore and modify, complete the implementation, then build independently. Tests check behaviour, so any correct solution passes.

Rows, not a column

Move a console.log so a grid prints row by row.

for (let r = 1; r <= 2; r++) {
  let line = "";
  for (let c = 1; c <= 3; c++) {
    line += "#";
    console.log(line);
  }
}

Multiplication grid

Combine two counters in a calculation.

const SIZE = 3;
// TODO: print a 3 by 3 multiplication grid, numbers separated by one space

Find matching pairs

Compare every pair once with an inner loop that starts after the outer index.

const prices = [12, 5, 8, 7, 3];
const TARGET = 15;

09Prediction

Commit to an answer first, then run the real code to compare.

let out = "";
for (let i = 1; i <= 2; i++) {
  for (let j = 1; j <= 2; j++) {
    out += i * j;
  }
}
console.log(out);

What is printed?

10Debugging investigation

Each store's total includes the stores before it

The weekly report shows the right total for Store 1, but every later store is far too high.

const sales = [[4, 6], [1, 5]];
let rowTotal = 0;
for (let r = 0; r < sales.length; r++) {
  for (let c = 0; c < sales[r].length; c++) {
    rowTotal += sales[r][c];
  }
  console.log(`Store ${r + 1}: ${rowTotal}`);
}

More cases in the Debugging Detective Laboratory

11Practical scenario

Seat map

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

Download the whole lesson folder (examples, exercises, solutions, tests) as ZIP

14Source files

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.

16AI learning prompts

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 explanation Nested 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 prediction Pattern 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.
Debugging Pattern 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 generation Grid 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 review Slow 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.