Sometimes, we want to stop a JavaScript for loop.
In this article, we’ll look at how to stop a JavaScript for loop.
How to stop a JavaScript for loop?
To stop a JavaScript for loop, we can use the break keyword.
For instance, we write
let arr = [1, 2, 3, 4, 5];
for (let ele of arr) {
if (ele > 3) {
break;
}
console.log(ele);
}
to add a for of loop to loop through the items in the arr array.
In it, we check if the ele variable, which is the item being looped through, is bigger than 3.
If it is, we use break to stop the loop.
Conclusion
To stop a JavaScript for loop, we can use the break keyword.