1 Matching Annotations
  1. Jul 2023
    1. A labeled statement is any statement that is prefixed with an identifier. You can jump to this label using a break or continue statement nested within the labeled statement
      Using a labeled continue with for loops

      ``js // The first for statement is labeled "loop1" loop1: for (let i = 0; i < 3; i++) { // The second for statement is labeled "loop2" loop2: for (let j = 0; j < 3; j++) { if (i === 1 && j === 1) { continue loop1; } console.log(i = ${i}, j = ${j}`); } }

      // Logs: // i = 0, j = 0 // i = 0, j = 1 // i = 0, j = 2 // i = 1, j = 0 // i = 2, j = 0 // i = 2, j = 1 // i = 2, j = 2 ```

      Using a labeled break with for loops

      ```js let i, j;

      // The first for statement is labeled "loop1" loop1: for (i = 0; i < 3; i++) { // The second for statement is labeled "loop2" loop2: for (j = 0; j < 3; j++) { if (i === 1 && j === 1) { break loop1; } console.log(i = ${i}, j = ${j}); } }

      // Logs: // i = 0, j = 0 // i = 0, j = 1 // i = 0, j = 2 // i = 1, j = 0 ```

      Using a labeled continue statement

      ```js // Numbers from 1 to 100 const items = Array.from({ length: 100 }, (_, i) => i + 1)); const tests = [ { pass: (item) => item % 2 === 0 }, { pass: (item) => item % 3 === 0 }, { pass: (item) => item % 5 === 0 }, ]; let itemsPassed = 0;

      itemIteration: for (const item of items) { for (const test of tests) { if (!test.pass(item)) { continue itemIteration; } }

      itemsPassed++; } js // Numbers from 1 to 100 const items = Array.from({ length: 100 }, (_, i) => i + 1)); const tests = [ { pass: (item) => item % 2 === 0 }, { pass: (item) => item % 3 === 0 }, { pass: (item) => item % 5 === 0 }, ]; let itemsPassed = 0;

      for (const item of items) { let passed = true; for (const test of tests) { if (!test.pass(item)) { passed = false; break; } } if (passed) { itemsPassed++; } } ```

      Using a labeled break statement

      ```js // Numbers from 1 to 100 const items = Array.from({ length: 100 }, (_, i) => i + 1)); const tests = [ { pass: (item) => item % 2 === 0 }, { pass: (item) => item % 3 === 0 }, { pass: (item) => item % 5 === 0 }, ]; let allPass = true;

      itemIteration: for (const item of items) { for (const test of tests) { if (!test.pass(item)) { allPass = false; break itemIteration; } } } ```

      Using a labeled block with break

      ```js foo: { console.log("face"); break foo; console.log("this will not be executed"); } console.log("swap");

      // Logs: // "face" // "swap" ```