| by Arround The Web | No comments

How to Stop a JavaScript for Loop

Sometimes, developers must stop the loop when the condition is met. To exit/stop the loop, use the “break” statement. For example, if you want to stop a loop when a certain variable reaches a certain value, use the break statement. It will exit the loop when that condition is met. The break statement can be utilized inside the loop to exit and execute the code immediately after the loop.

This article will describe the way to stop the for loop in JavaScript.

How to Stop a JavaScript “for” Loop?

A “for” loop in JavaScript can be stopped using the “break” statement. The break statement is utilized to exit a loop early before the loop’s conditional expression is false. To exit or stop the loop, use the break statement within the if statement.

Example 1: Print Numbers and Stop the Loop When the Number “5” is Printed

In the given example, the loop will only run 5 times and stop when the variable “i” reaches the value of 5:

for (let i = 0; i <10; i++) {
console.log(i);
if (i == 5) {
break;
 }
}

After exiting the loop, the remaining code will execute:

console.log(&quot;Loop Stop&quot;);

It can be observed that the loop will run until the value 5 is printed, then the loop is immediately stopped and continue to execute the remaining code:

Example 2: Stop Loop When the Element “10” is Found in Array

Create an array of even numbers:

var array = [2, 4, 6, 8, 10, 12, 14, 16, 18];

Iterate the array using “for” loop and stop when the element “10” is found in the array:

for (let i = 0; i < array.length; i++) {
if (array[i] == 10) {
break;
 }
console.log(array[i]);
}

Execute the remaining code after stopping the loop:

console.log(&quot;Loop Stop&quot;);

Output

The break statement is used in the for loops, such as “for”, “for…of” loop, and “for…in” loop, while using it in the “forEach” loop throws an error.

Example 3: Use the “break” Statement in the “forEach” Loop

Use the “forEach” loop to iterate the array and stop when the element 10 is found:

array.forEach(elem => {
if (elem == 10) {
break;
 }
});
console.log("Loop Stop");

It can be observed that the “break” statement does not stop the loop in forEach loop

That’s all about stopping the for loop in JavaScript.

Conclusion

To stop the “for” loop in JavaScript, use the “break” statement. It is used inside the loop to exit/stop the loop and continue executing the remaining code. Moreover, the break statement can be utilized to stop the “for”, “for…of”, and “for…in” loops. While the “forEach” loop never uses the “break” statement to stop the looping, it gives an error. This article demonstrated the way to stop the for loop in JavaScript.

Share Button

Source: linuxhint.com

Leave a Reply