JavaScript Break statement; In this tutorial, you will learn JavaScript Break statement with the help of examples.
JavaScript Break Statement
- The
label
statement - JavaScript
break
statement - Syntax of JavaScript
break
statement - Example 1:
break
statement with for loop - Example 2: Using
break
statement to exit nested loop
The label
statement
In JavaScript, you can label a statement for later use.
Syntax of the label
statement:
label: statement;
The label can be any valid identifier.
Example 1: labels the loop using the mylb
label.
mylb: for (let i = 0; i < 5; i++) { console.log(i); }
In below, we will take an example of a break statement with label. You can also reference the label by using the break
or continue
statement. And you can also use the label with javascript loop such as for
, do-while
, and while
loop.
JavaScript break
statement
As the name suggests, The javascript break
statement breaks/stopped the execution in programs/scripts.
Syntax of JavaScript break
statement
break;
Example 1: break
statement with for loop
See the following example ofbreak
statement with for loop:
<script> var i = 1; for (i; i < 10; i++) { if (i % 5 == 0) { break; } } document.write(i + "<br>") </script>
The output of the script shown below:
5
How it works:
- First, declare a variable
i
and initialize it to 1. - Next, specified test condition.
- After that, Increase the value of
i
by 1 in each iteration of the loop. - Use if statement with break.
- Next, print the value of
i
.
In this above example, the for
loop increments the variable i from 1 to 10. In the body of the loop, the if
statement checks if i is variable divisible by 5 in each iteration of the loop. If so, the break
statement is executed and the loop is terminated.
The control is passed to the next statement outside the loop that outputs the variable i
to the console window.
Example 2: Using break
statement to exit nested loop
As mentioned above, you use the break
statement to terminate a label statement and transfer control to the next statement following the terminated statement.
The syntax is as follows:
break label;
The break
statement is typically used to exit the nested loop. See the following example.
<script> let iterations = 0; top: for (let i = 0; i < 4; i++) { for (let j = 0; j < 4; j++) { iterations++; if (i === 2 && j === 2) { break top; } } } document.write(iterations + "<br>") </script>
The output of the script shown below:
11
Here,
- First, the variable
iterations
is set to zero. - Second, both loops increase the variable
i
andj
from1
to4
. In the inner loop, we increase theiteration
variable and use anif
statement to check bothi
andj
equal 2. If so, thebreak
statement terminates both loops and passes the control over the next statement following the loop.
Conclusion
In this tutorial, you have learned what is break statement and how to use the JavaScript break
statement to control the code execution of for loop and nested loop.