In this article, we will explain how to break ForEach Loop in JavaScript. Basically, many Programmers can use the forEach() method In JavaScript to iterate through the array of elements.

So, it is a callback function, which we can pass as a parameter of the forEach() method for every array element.

In this case, we may need to require to stop the forEach() loop after executing the callback function for some elements.

If you want then buy a good, reliable, secure web hosting service  from here: click here

Also, we can use the ‘break’ keyword with a normal loop to stop it, as shown below in the example.

for(let i = 0; i < length; i++){
// code
if( some condition ){
break;
}
}

Although, we can’t use the ‘break’ keyword with the forEach() method like in the below example.

array.forEach(element => {
// code
if( some condition ){
break;
}
});

But the above code will not stop the execution of the forEach() loop.

Now, in this article, we will teach various approaches to stop forEach() loop in JavaScript.

Previous JavaScript Articles

The best solution to stop the execution of the forEach() method is to replace the forEach() loop with the normal for-loop and use the break keyword to stop its execution like the below code.

for ( ){
if (condition) {
break;
}
}

So, In the above syntax, we stop the execution of the for-loop using the break keyword when a particular condition becomes true.

<html>
<body>
<h2>Using the normal for-loop with break keyword to stop the execution of for-loop. </h2>
<div id = "output"> </div>
<script>
let output = document.getElementById('output');
let arrayElements = [10, 20, 30, 40, 50, 60, 70, 80, 90];
output.innerHTML += "Some array elements are "
for (let k = 0; k < arrayElements.length; k++) {
if (arrayElements[k] > 30) {
break;
}
output.innerHTML += arrayElements[k] + " , ";
}
</script>
</body>
</html>
If you want then buy a good, reliable, secure web hosting service  from here: click here

That’s it. If you enjoyed reading this article and have more questions please reach out to our support team via live chat or email and we would be glad to help you. we provide server hosting for all types of need and we can even get your server up and running with the service of your choice.