JavaScript and the Use of Break

javascript break usage
10 November 2024

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 HTML
for (let i = 0; i < 10; i++) \- A for loop that runs from 0 to less than 10
if (i === 3) \- A condition that checks if the value of i is equal to 3
break; \- The break statement that allows the loop to stop if the condition is met
console.log(i); \- Displays the value of i in the console until it reaches the condition
<\/script> \- Ends the JavaScript script

FAQ

?

Why should we use the break statement?

?

Where is the break statement used?

?

Can break be used in a while loop as well?