Labeled Break And Continue Escape Nested Loops

A label lets continue restart the outer loop and break leave both loops at once, where an unlabeled break only exits the innermost iteration.

JavascriptData Integrity

Code

javascriptsnippet
49 lines
// 有标签的 continue:直接跳到外层循环的下一轮,内层剩余迭代全部放弃
const grid = [
  [1, 2, 3],
  [4, 0, 6],
  [7, 8, 9],
];

outer: for (const [rowIndex, row] of grid.entries()) {
  for (const value of row) {
    if (value === 0) {
      console.log('zero in row', rowIndex, '- skip whole row');
      continue outer;
    }
  }
  console.log('row', rowIndex, 'clean:', row.join(','));
}

// 有标签的 break:一次跳出两层,而不是只退出内层
function firstNegativeRow(rows) {
  let found = null;
  search: for (const [i, row] of rows.entries()) {
    for (const value of row) {
      if (value < 0) {
        found = i;
        break search;
      }
    }
  }
  return found;
}

const temps = [
  [3, 4],
  [5, -1],
  [-2, 8],
];
console.log('first negative row:', firstNegativeRow(temps));

// 无标签 break 的对照:只能退出内层,外层继续
let count = 0;
for (const row of temps) {
  for (const value of row) {
    if (value < 0) {
      count += 1;
      break;
    }
  }
}
console.log('unlabeled break visits rows containing negatives:', count, 'of', temps.length);

Output

Captured from a sandboxed run of this snippet in the build pipeline.

row 0 clean: 1,2,3
zero in row 1 - skip whole row
row 2 clean: 7,8,9
first negative row: 1
unlabeled break visits rows containing negatives: 2 of 3

How the snippet works

Labeled Break And Continue Escape Nested Loops keeps everything in the function firstNegativeRow.

Iteration is nested: for (const value of row) frames the pass, for (const row of temps) does the per-item step.

Watch out for

  • The environment needs no preparation beyond having the interpreter or compiler.

Applying it

The main signature reads function firstNegativeRow(rows)

Running the file prints labeled results such as zero in row, row, first negative row: — each operation’s effect is visible in the output.

Statements that matter

let found = null;
continue outer;
let count = 0;

Interactive Tools for This Topic

FAQ

Any setup needed beyond the language runtime?
None — the language runtime is the only requirement. The file defines `firstNegativeRow` at load time.