Break out of nested loops in JavaScript
Intermediate · 4 min read
Seat maps, game boards, spreadsheets and calendars are all grids: rows, and items in each row. To walk a grid you put one loop inside another. That is easy. Stopping both loops at once, the moment you find what you were looking for, is where people get caught out.
In this tutorial you will build the seating chart of a small bus, three rows of four seats, and then find the first free seat. You will see why a plain break gives the wrong seat, and fix it with a label. You need to know how for and for...of loops work, what break does, and what includes does (it checks whether an array contains a value).
A loop inside a loop
The outer loop picks a row. For each row, the inner loop goes through every seat in it:
for (const row of ['A', 'B']) {
for (let seat = 1; seat <= 3; seat++) {
console.log(row + seat); // A1, A2, A3, B1, B2, B3
}
}
The inner loop runs completely, from start to finish, once for every turn of the outer loop. So the inner body runs rows times seats: here 2 times 3, which is 6 times.
break only leaves one loop
break stops the loop it is written in, the nearest one around it. Inside a nested loop, that is the inner loop. The outer loop carries on with its next turn as if nothing happened.
Here is the exercise. Try it yourself first if you like, or read on and we will build it together.
79 Nested loops, and breaking out of both
fairBuild a seating chart of three rows by four seats, then find the first free seat. Leaving a nested loop early needs more than break: show what a plain break does instead.
Stuck? Three hints, smallest first
- 1. The outer loop picks the row, the inner one the seat. Push a row array per outer turn.
- 2. A plain
breakonly ends the loop it is written in. - 3. A label before the outer loop, and
break label, leaves both.
Step 1: build the chart
Make one array per row and push it into the chart:
const ROWS = ['A', 'B', 'C'];
const PER_ROW = 4;
function chartOf(rows, perRow) {
const out = [];
for (const row of rows) {
const line = [];
for (let seat = 1; seat <= perRow; seat++) line.push(row + seat);
out.push(line);
}
return out;
}
const chart = chartOf(ROWS, PER_ROW);
console.log(chart.length); // 3
console.log(chart[0]); // [ 'A1', 'A2', 'A3', 'A4' ]
console.log(chart[1][2]); // B3
console.log(chart.flat().length); // 12
The result is an array of arrays. chart[1] is row B, and chart[1][2] is the third seat in it (counting from 0), B3. flat() joins the rows into one list of 12 seats.
Step 2: count the turns
Before a nested loop touches real data, it helps to know how often its inner body runs:
const ROWS = ['A', 'B', 'C'];
const PER_ROW = 4;
let visits = 0;
for (const row of ROWS) {
for (let seat = 1; seat <= PER_ROW; seat++) visits++;
}
console.log(visits); // 12
3 rows times 4 seats is 12. Double both and it is 6 times 8, which is 48: four times the work. Nested loops grow quickly.
Step 3: find a free seat with a plain break
Seats A1 to A4 and B1 are taken. The first free seat should be B2. Here is the obvious attempt:
const ROWS = ['A', 'B', 'C'];
const PER_ROW = 4;
function firstFreeBuggy(taken) {
let found = null;
for (const row of ROWS) {
for (let seat = 1; seat <= PER_ROW; seat++) {
const label = row + seat;
if (!taken.includes(label)) {
found = label;
break;
}
}
}
return found;
}
console.log(firstFreeBuggy(['A1', 'A2', 'A3', 'A4', 'B1'])); // C1
It answers C1, a seat that really is free, so the bug is easy to miss. Follow it through. In row B, it finds B2, saves it, and breaks out of the inner loop. The outer loop then moves on to row C, finds C1 free, and saves that over B2.
Step 4: a labeled break
A label is a name followed by a colon, written just before a loop. break with that name leaves the labeled loop, and every loop inside it:
const ROWS = ['A', 'B', 'C'];
const PER_ROW = 4;
function firstFree(taken) {
let found = null;
search:
for (const row of ROWS) {
for (let seat = 1; seat <= PER_ROW; seat++) {
const label = row + seat;
if (!taken.includes(label)) {
found = label;
break search;
}
}
}
return found;
}
console.log(firstFree(['A1', 'A2', 'A3', 'A4', 'B1'])); // B2
search: names the outer loop. break search stops both loops at once, so B2 is the answer. Labels look odd the first time you see them, but this is exactly what they are for.
Step 5: a full bus, and another way out
If every seat is taken, the loops finish without finding anything, and found stays null:
function firstFreeIn(chart, taken) {
for (const line of chart) {
for (const label of line) {
if (!taken.includes(label)) return label;
}
}
return null;
}
const chart = [['A1', 'A2'], ['B1', 'B2']];
console.log(firstFreeIn(chart, ['A1'])); // A2
console.log(firstFreeIn(chart, chart.flat())); // null
This version also shows the other common fix. When the nested loops sit in their own function, return leaves the whole function at once, both loops included, and you don't need a label.
The full solution
The answer panel builds and prints the chart, counts the 12 visits, and runs the labeled and plain versions side by side. Its checks cover the chart's shape, B2 against C1, and a full bus. Press Run to see the output.
const ROWS = ['A', 'B', 'C'];
const PER_ROW = 4;
function chartOf(rows, perRow) {
const out = [];
for (const row of rows) {
const line = [];
for (let seat = 1; seat <= perRow; seat++) line.push(row + seat);
out.push(line);
}
return out;
}
const chart = chartOf(ROWS, PER_ROW);
// The body of a nested loop runs rows x seats times. Worth knowing before the
// numbers get large.
let visits = 0;
for (const row of ROWS) {
for (let seat = 1; seat <= PER_ROW; seat++) visits++;
}
// A labelled break leaves BOTH loops.
function firstFree(taken) {
let found = null;
search:
for (const row of ROWS) {
for (let seat = 1; seat <= PER_ROW; seat++) {
const label = row + seat;
if (!taken.includes(label)) {
found = label;
break search;
}
}
}
return found;
}
// The same walk with a plain break: it only ends the row, so the outer loop
// carries on and overwrites the answer with a later row's first free seat.
function firstFreeBuggy(taken) {
let found = null;
for (const row of ROWS) {
for (let seat = 1; seat <= PER_ROW; seat++) {
const label = row + seat;
if (!taken.includes(label)) {
found = label;
break;
}
}
}
return found;
}
const taken = ['A1', 'A2', 'A3', 'A4', 'B1'];
console.log(chart.map((row) => row.join(' ')).join('\n'));
console.log('labelled break:', firstFree(taken), '| plain break:', firstFreeBuggy(taken));
Output
8 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 8 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('three rows', chart.length, 3);
test('four seats in each', chart[0], ['A1', 'A2', 'A3', 'A4']);
test('outer index picks the row, inner one the seat', chart[1][2], 'B3');
test('twelve seats in all', chart.flat().length, 12);
test('and the inner body ran exactly twelve times', visits, 12);
test('a labelled break finds the first free seat', firstFree(taken), 'B2');
test('a plain break only leaves the row, so the walk continues', firstFreeBuggy(taken), 'C1');
test('a full bus has nothing free', firstFree(chart.flat()), null);
Nesting multiplies: three rows by four seats is twelve turns of the inner body, and doubling both quadruples the work. That is the cost to keep in view when a nested loop sits over real data.
firstFreeBuggy is the bug this exercise exists for. It looks correct, it returns a genuinely free seat, and it is wrong — break ended the inner loop only, so rows B and C were still visited and found was reassigned twice. The label reads oddly the first time you meet it, but break search is the honest fix. The alternative is to stop nesting: put the inner loop in its own function and return from it, which leaves the whole thing at once and needs no label.
Common mistakes
- Expecting
breakto leave both loops. It only leaves the inner one. Use a label, orreturnfrom a function. - Trusting an answer because it looks valid.
C1is free, just not the first free seat. Test with a case where the right answer is in the middle. - Swapping the loops. With seats outside and rows inside, you would walk the bus column by column and find
C1beforeB2.
Try it yourself
- Change
firstFreeto return the row and seat number separately, like{ row: 'B', seat: 2 }. - Count how many free seats there are in each row and return an object like
{ A: 0, B: 3, C: 4 }. - Find the first row with two free seats next to each other.