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

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:

every executes the provided callback function once for each element present in the array until it finds one where callback returns a false value. If such an element is found, the every method 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.

Leave a Comment