How to terminate javascript forEach()?


You can't break from the forEach method and it doesn't provide to escape the loop (other than throwing an exception).

You can use other functions like _.find from lodash instead −

_.find − it breaks out of the loop when the element is found. For example,

Example

_.find([1, 2, 3, 4], (element) => {
   // Check your condition here
   if (element === 2) {
      return true;
   }
   // Do what you want with the elements here
   // ...
});

Throw an exception from forEach. For example,

Example

try {
   [1, 2, 3, 4].forEach((element) => {
      // Check your condition here
      if (element === 2) {
         throw new Error();
      }
      // Do what you want with the elements here
      // ...
   })
} catch (e) {
   // Do nothing.
}

Updated on: 27-Nov-2019

369 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements