How to stop forEach() method in JavaScript ?
Last Updated :
13 Jan, 2023
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) {
if (item.localeCompare( "boar" ) == 0)
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) {
if (loop.stop){ return ;}
console.log(item);
if (item == 87) {
loop.stop = true ;
}
});
|
Output:
90
87
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...