Skip to content
Related Articles

Related Articles

How to stop forEach() method in JavaScript ?

View Discussion
Improve Article
Save Article
  • Last Updated : 03 Dec, 2020

Stopping a forEach() loop seems almost like an impossible task but here are a few tricks by which we might do it.

Sample example using forEach():

var sum = 0;
var number = [90, 4, 22, 48];

function myFunction(item) {
    sum += item;

Tricks to stop forEach() loop:

Method 1:The following method demonstrates using try-catch block. The following code demonstrates surrounding the thing with a try-catch block and throwing an exception when forEach loop break.



var animals=["pig", "lion", "boar", "rabbit"];
try {
    function myFunction(item) {
        // Condition for breaking the loop
        if(item.localeCompare("boar") == 0) 
        /* skips rest of the statements in the
        function and goes to the catch block */
        throw new Exception("Time to end the loop"); 
catch(e) {
    console.log("Loop has ended");


Loop has ended

Method 2: This method does not actually break from the forEach() loop but thinks of it as a continuous statement against all other elements i.e. it skips all other elements after the element that satisfies the given condition. 


var ary = [90, 87, 45, 99];
ary.forEach(function loop(item) {
    // This statement acts like a continue
    // statement for the remaining elements
    // when the condition is satisfied
    if(loop.stop){ return;} 
    // Prints the element to the console
    // This statement acts like a condition
    // and prevents the execution of the
     // loop for the remaining elements
    if(item == 87) { 
        loop.stop = true


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!