JavaScript Break

The break statement in JavaScript is used to exit a loop or switch statement before it has completed its natural execution. It immediately terminates the enclosing loop or switch and transfers control to the statement following the terminated statement.

1. Syntax of break Statement:

break;

Try It Now

2. break in a for Loop:

for (let i = 0; i < 10; i++) {
    if (i === 5) {
        break;
    }
    console.log("i = " + i);
}

Try It Now

Output:

i = 0
i = 1
i = 2
i = 3
i = 4

Try It Now

Explanation:

  • The loop stops execution when i equals 5 due to the break statement.

 

3. break in a while Loop:

let count = 0;

while (count < 10) {
    if (count === 5) {
        break;
    }
    console.log("Count = " + count);
    count++;
}

Try It Now

Output:

Count = 0
Count = 1
Count = 2
Count = 3
Count = 4

Try It Now

Explanation:

  • The while loop stops when count equals 5 due to the break statement.

 

4. break in a switch Statement:

let color = "red";

switch (color) {
    case "red":
        console.log("Color is red");
        break;
    case "blue":
        console.log("Color is blue");
        break;
    default:
        console.log("Color is not red or blue");
}

Try It Now

Output:

Color is red

Try It Now

5. break in Nested Loops:

for (let i = 0; i < 3; i++) {
    for (let j = 0; j < 3; j++) {
        if (j === 2) {
            break;
        }
        console.log(`i = ${i}, j = ${j}`);
    }
}

Try It Now

Output:

i = 0, j = 0
i = 0, j = 1
i = 1, j = 0
i = 1, j = 1
i = 2, j = 0
i = 2, j = 1

Try It Now

Explanation:

  • The break statement exits the inner loop when j equals 2 but allows the outer loop to continue.

6. break in a Labeled Statement:

In JavaScript, you can use labels to break out of nested loops or a specific loop. A label identifies a loop or a block of code.

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}`);
    }
}

Try It Now

Output:

i = 0, j = 0
i = 0, j = 1
i = 0, j = 2
i = 1, j = 0

Try It Now

Explanation:

  • The break outerLoop; statement exits the outerLoop entirely, skipping the remaining iterations.

Conclusion:

  • The break statement is a powerful tool for controlling the flow of loops and switch statements.
  • It allows for more precise and controlled termination of loops and cases, improving code readability and logic management.
  • However, use break carefully to ensure that it does not unintentionally terminate the loop or block, leading to unexpected results.