How to break the _.each function in underscore.js


You can't break from each method. It copies the native forEach method's behavior and the native forEach doesn't provide to escape the loop (other than throwing an exception).

You can use other functions like −

  • _.find: it breaks out of the loop when the element is found. For 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 each. For example,

try {
   _([1, 2, 3, 4]).each((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: 02-Dec-2019

224 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements