JavaScript Break , Continue JavaScript Labels​

In JavaScript, break and continue are keywords used in loops to control the flow of execution.

break Statement

The break statement is used to exit a loop prematurely. When encountered inside a loop, it immediately terminates the loop and the program continues with the next statement after the loop.

*Syntax:*
javascript
for (initializer; condition; iteration) {
   // code to be executed
   if (conditionToBreak) {
      break;
   }
   // more code
}

Example

javascript
for (let i = 0; i < 5; i++) {
      console.log(i);
      if (i === 2) {
          break;
      }
}
// Output: 0 1 2 

In this example, the loop will break when i is equal to 2, so only 0, 1, and 2 will be printed.

continue Statement

The continue statement is used to skip the rest of the code inside a loop for the current iteration and proceed to the next iteration.

*Syntax:*
javascript
for (initializer; condition; iteration) {
    // code to be executed
    if (conditionToContinue) {
       continue;
    }
    // more code
}

Example

javascript
for (let i = 0; i < 5; i++) {
   if (i === 2) {
       continue;
   }
   console.log(i);
}
// Output: 0 1 3 4

In this example, the loop will skip the iteration when i is equal to 2, so it won’t print anything for that iteration.

Labels in JavaScript

Labels are identifiers attached to statements in JavaScript. They are often used with loops and the break and continue statements to control the flow of nested loops.

*Syntax:*
javascript
labelName: for (initializer; condition; iteration) {
       // code to be executed
       if (conditionToBreak) {
          break labelName;
       }
      // more code
}

Example

javascript
outerLoop: for (let i = 0; i < 3; i++) {
       for (let j = 0; j < 3; j++) {
           if (i === 1 && j === 1) {
               break outerLoop;
           }
           console.log(`i=${i}, j=${j}`);
       }
}
// Output: i=0, j=0 i=0, j=1 i=0, j=2

In this example, the break outerLoop; statement will exit both the inner and outer loops when i is 1 and j is 1. Labels are useful when dealing with nested loops and you want to control the flow at an outer level.