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 a try-catch block. The following code demonstrates surrounding the thing with a try-catch block and throwing an exception when forEach loop break.
Example: This example uses the above-approach.
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.Â
Example: This example shows the use of the above-approach.
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