How to stop forEach() method in JavaScript?

In JavaScript, Programmers can use the forEach() method to iterate through the array of elements. We can call a callback function, which we can pass as a parameter of the forEach() method for every array element.

Sometimes, we may require to stop the forEach() loop after executing the callback function for some elements. We can use the ‘break’ keyword with a normal loop to stop it, as shown below.

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

But we can’t use the ‘break’ keyword with the forEach() method.

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

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

Use the return keyword

The return keyword stops the execution of the code. In the forEach() loop, it works as a continue statement.

Syntax

Users can follow the syntax below to use the return keyword to stop the execution of the forEach() method.

array.forEach(function (element, index) {
   if (condition) {
      return; 
   }
});

In the above syntax, if the condition becomes true, it will not execute the code of the callback function for the element.

Stop the forEach() loop by throwing the exception

Another way to stop the execution of the forEach() loop is using the try-catch statement. We can throw the error when we want to stop the execution of the forEach() method. Also, we can catch the error in the ‘catch’ block. We can execute whatever code we need to execute after the forEach() method in the ‘finally’ block.

Syntax

Users can follow the syntax below to stop the forEach() method using the try-catch statement.

try {
   array.forEach((ele) => {
      if (condition) {
         throw new Error("Break the loop.")
      }
   })
} catch (error) {
}

In the above syntax, we have used the throw keyword to throw the exception and break the forEach() method.