Skip to content
Related Articles

Related Articles

How to stop forEach() method in JavaScript ?
  • 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];
number.forEach(myFunction);

function myFunction(item) {
    sum += item;
}
console.log(sum);

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.

Example:



Javascript




var animals=["pig", "lion", "boar", "rabbit"];
  
try {
    animals.forEach(myFunction);
  
    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"); 
        console.log(item);
    }
}
catch(e) {
    console.log("Loop has ended");
}

Output:

pig
lion
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. 

Javascript




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
    console.log(item);
      
    // This statement acts like a condition
    // and prevents the execution of the
     // loop for the remaining elements
    if(item == 87) { 
        loop.stop = true
    
});
Output:
90
87

full-stack-img

My Personal Notes arrow_drop_up
Recommended Articles
Page :