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:
console.log(i);
if (i == 5) {
break;
}
}
After exiting the loop, the remaining code will execute:
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:
Iterate the array using “for” loop and stop when the element “10” is found in the array:
if (array[i] == 10) {
break;
}
console.log(array[i]);
}
Execute the remaining code after stopping the loop:
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:
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.