JavaScript break statement; Through this tutorial, i am going to show you about break statement in javaScript and it’s usage with example.
JavaScript Break Statement
- JavaScript
break
statement - Syntax of
break
statement - Example 1:
break
statement with for loop - Example 2: Using
break
statement to exit nested 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
Explanation of above program;
- To declare a variable
i
and initialize it to 1. - Then, 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
.
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
Explanation of above program;
- 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.