Sunday, September 22, 2024
Google search engine
HomeLanguagesJavascriptJavaScript Break Statement

JavaScript Break Statement

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, we will use the break statement in the switch block.

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

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

Example 2: In this example, we will use the break statement in the switch block.

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

In the above 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 appeared.

Example 3: In this example, we will use the break statement in the for loop.

Javascript




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


Output

1
2
3

In the above 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.

Supported browsers:

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

RELATED ARTICLES

Most Popular

Recent Comments