In the JavaScript programming language, the break statement is one of the conditional and control statements that is used to terminate the execution of statements within loops and switch blocks. This statement allows you to exit a loop or switch statement as soon as the specified condition is met.
Assume you have a loop that is currently executing and you want to exit it at specific points where a specific condition is true. Immediately in such situations, the break statement comes into play. Using this statement will prevent further processing and exit at the same point.
Now consider the following example that demonstrates how to use the break statement in a for loop. This example shows a clear instance of practical and actual use of this statement in JavaScript.
Example of Using Break in JavaScript
Here is a simple example that uses the break statement in a for loop to stop the loop if it hits the number 3:
<script>
for (let i = 0; i < 10; i++) {
if (i === 3) {
break;
}
console.log(i);
}
<\/script>
Line by Line Code Explanation
<script>
\- Begins the JavaScript script in HTMLfor (let i = 0; i < 10; i++)
\- A for loop that runs from 0 to less than 10if (i === 3)
\- A condition that checks if the value of i is equal to 3break;
\- The break statement that allows the loop to stop if the condition is metconsole.log(i);
\- Displays the value of i in the console until it reaches the condition<\/script>
\- Ends the JavaScript script