How to use the break statement In Javascript

The break Statement comes out of the loop when the condition is true. It breaks out of the loop or switch. 

Example: In this example, the break statement is used to exit the for loop when the element “orange” is found in the fruits array. The break statement can be used to exit a loop or switch statement and stop the execution of the script.

Javascript




let fruits = ["banana", "apple", "orange", "grape", "strawberry"];
 
for (let i = 0; i < fruits.length; i++) {
    if (fruits[i] === "orange") {
        break;
    }
    console.log(fruits[i]);
}


Output

banana
apple

Different Ways to Abort JavaScript Execution

Aborting JavaScript execution can help us to write more robust, secure, and efficient code by preventing unexpected errors and behaviors.

Similar Reads

Possible reasons why we need to abort JavaScript execution are:

We might need to abort execution when an error occurs to prevent further execution of the code and avoid unexpected behavior or data corruption. We might need to abort execution when user input is invalid to prevent the code from running with incorrect or unexpected input. We might need to abort execution in the middle of a loop if a specific condition is met, or if we have found the result we were looking for. We might need to abort execution in some cases to optimize performance, such as when using setInterval or setTimeout, where we might need to stop the execution of a function or loop after a specific amount of time. In some cases, it might be necessary to abort execution to prevent malicious code from running, or to prevent sensitive data from being accessed....

Using the return statement

Return statements in a programming language are used to skip the currently executing function and return to the caller function....

Using the break statement

...

Using the continue statement

The break Statement comes out of the loop when the condition is true. It breaks out of the loop or switch....

Using the try-catch statement

...

Using the window.stop Method

The continue statement in Javascript is used to break the iteration of the loop and follows with the next iteration. The break in the iteration is possible only when the specified condition going to occur....

Using the clearTimeout() and clearInterval() Methods

...