JavaScript - Break Statement
JavaScript - Break Statement
Thebreakstatement in JavaScript terminates the loop or switch case statement. When you use thebreakstatement with the loop, the control flow jumps out of the loop and continues to execute the other code.
Thebreakstatement can also be used to jump a labeled statement when used within that labeled statement. It is a useful tool for controlling the flow of execution in your JavaScript code.
Syntax
The syntax of break statement in JavaScript is as follows β
break;
OR
break [label];The label is optional with a break statement.
Note In the next chapter, we will learn to use the break statement with the label inside the loop.
Flow Chart
The flow chart of a break statement would look as follows β
Example (break statement with for loop)
In the example below, we used the for loop to make iterations. We added the conditional expression in the loop using the βifβ statement. When the value of βxβ is 5, it will βbreakβ the loop using the break statement.
The below code prints only 1 to 4 values in the output.
Output
Entering the loop.
1
2
3
4
Exiting the loop!Example (break statement with the while loop)
The code below demonstrates the while loop with the βbreakβ statement. In the while loop, whenever the value of x is either 3 or 7, it will terminate the loop using the βbreakβ statement.
In the code, we update the value after checking the condition. So, it will print 3 first and then terminate the loop in the next iteration.
Output
Entering the loop.
2
3
Exiting the loop!Break statement with nested loops
You can use the βbreakβ statement to jump out of any loop when you have nested loops. For example, if you use the βbreakβ statement with the parent loop, the code will also terminate all iterations of the nested loop. Using the βbreakβ statement with the nested loop will terminate only the nested loop.
Example
In the example below, x is a looping variable for the parent loop, and y is a looping variable for a child loop.
In the nested loop, whenever y becomes 3, it will break the loop; in the outer loop, whenever x becomes 3, it will break the loop. You wonβt see x > 3 or y > 2 in the output.
Output
Entering the loop.
1 1
1 2
2 1
2 2
3 1
3 2
Exiting the loop!Break statement with switch case statement
The switch case statement executes one of the code blocks from multiple based on the conditional expression. The βbreakβ statement terminates the switch case statement after matching one or more cases with the conditional expressionβs value.
Example
In the below code, we used the βbreakβ statement with each case. Here, the value of variable p works as a conditional expression for the switch case statement. It matches with βcase 10β. So, the code will execute that particular code block and terminate the switch case statement using the βbreakβ statement.
Output
p is 10