How to terminate javascript forEach()?

JavascriptFront End TechnologyObject Oriented Programming

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.
}
raja
Published on 27-Nov-2019 12:17:14
Advertisements