I\'m looking for a way to stop iterations of underscore.js _.each() method, but can\'t find the solution. jQuery .each() can break if you do
You can't break from the each method—it emulates the native forEach method's behavior, and the native forEach doesn't provide to escape the loop (other than throwing an exception).
However, all hope is not lost! You can use the Array.every method. :)
From that link:
everyexecutes the providedcallbackfunction once for each element present in the array until it finds one wherecallbackreturns a false value. If such an element is found, theeverymethod immediately returns false.
In other words, you could do something convoluted like this (link to JSFiddle):
[1, 2, 3, 4].every(function(n) {
alert(n);
return n !== 3;
});
This will alert 1 through 3, and then "break" out of the loop.
You're using underscore.js, so you'll be pleased to learn that it does provide an every method—they call it every, but as that link mentions, they also provide an alias called all.