This text will describe the best way to cease the for loop in JavaScript.
Easy methods to Cease a JavaScript “for” Loop?
A “for” loop in JavaScript might be stopped utilizing the “break” assertion. The break assertion is utilized to exit a loop early earlier than the loop’s conditional expression is fake. To exit or cease the loop, use the break assertion throughout the if assertion.
Instance 1: Print Numbers and Cease the Loop When the Quantity “5” is Printed
Within the given instance, the loop will solely run 5 occasions and cease when the variable “i” reaches the worth 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("Loop Cease");
It may be noticed that the loop will run till the worth 5 is printed, then the loop is straight away stopped and proceed to execute the remaining code:
Instance 2: Cease Loop When the Aspect “10” is Present in Array
Create an array of even numbers:
var array = [2, 4, 6, 8, 10, 12, 14, 16, 18];
Iterate the array utilizing “for” loop and cease when the aspect “10” is discovered within the array:
for (let i = 0; i < array.size; i++) {
if (array[i] == 10) {
break;
}
console.log(array[i]);
}
Execute the remaining code after stopping the loop:
console.log("Loop Cease");
Output
The break assertion is used within the for loops, reminiscent of “for”, “for…of” loop, and “for…in” loop, whereas utilizing it within the “forEach” loop throws an error.
Instance 3: Use the “break” Assertion within the “forEach” Loop
Use the “forEach” loop to iterate the array and cease when the aspect 10 is discovered:
array.forEach(elem => {
if (elem == 10) {
break;
}
});
console.log(“Loop Cease”);
It may be noticed that the “break” assertion doesn’t cease the loop in forEach loop
That’s all about stopping the for loop in JavaScript.
Conclusion
To cease the “for” loop in JavaScript, use the “break” assertion. It’s used contained in the loop to exit/cease the loop and proceed executing the remaining code. Furthermore, the break assertion might be utilized to cease the “for”, “for…of”, and “for…in” loops. Whereas the “forEach” loop by no means makes use of the “break” assertion to cease the looping, it offers an error. This text demonstrated the best way to cease the for loop in JavaScript.