Open In App

JavaScript Break Statement

JavaScript break statement is used to terminate the execution of the loop or the switch statement when the condition is true.

Syntax:

break;

Using Labels

A label reference can be used by the break statement to exit any JavaScript code block. Only a loop or a switch can be used with the break in the absence of a label.



break labelName;

Example 1: In this example, the switch case is executed if the condition is true then it breaks out and the next case is not checked.




const fruit = "Mango";
 
switch (fruit) {
    case "Apple":
        console.log("Apple is healthy for our body");
        break;
    case "Mango":
        console.log("Mango is a National fruit of India");
        break;
    default:
        console.log("I don't like fruits.");
}

Output

Mango is a National fruit of India

Example 2: In this example, the fruit name is apple but the given output is for the two cases. This is because of the break statement. In the case of Apple, we are not using a break statement which means the block will run for the next case also till the break statement not appear.




const fruit = "Apple";
 
switch (fruit) {
    case "Apple":
        console.log("Apple is healthy for our body");
    case "Mango":
        console.log("Mango is a National fruit of India");
        break;
    default:
        console.log("I don't like fruits.");
}

Output
Apple is healthy for our body
Mango is a National fruit of India

Example 3: In this example, the loop iterate from 1 to 6 when it is equal to 4 then the condition becomes true, and code breaks out to the loop.




for (let i = 1; i < 6; i++) {
    if (i == 4) break;
    console.log(i);
}

Output
1
2
3

Example 4: In this example, break statement can is used with while and do-while loop.




// Using break in a while loop
let i = 1;
while (i <= 5) {
    console.log(i);
    if (i === 3) {
        break;
    }
    i++;
}
 
// Using break in a do-while loop
let j = 1;
do {
    console.log(j);
    if (j === 3) {
        break;
    }
    j++;
} while (j <= 5);

Output
1
2
3
1
2
3

Supported browsers:


Article Tags :