Open In App

JavaScript Break Statement

Last Updated : 18 Dec, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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

  • In a switch, code breaks out and the execution of code is stopped. 
  • In a loop, it breaks out to the loop but the code after the loop is executed.

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.

Javascript




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.

Javascript




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.

Javascript




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.

Javascript




// 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:

  • Google Chrome
  • Microsoft Edge
  • Firefox
  • Opera
  • Safari


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads