Skip to content

Instantly share code, notes, and snippets.

@benshimmin
Created March 25, 2014 18:39
Show Gist options
  • Save benshimmin/9768356 to your computer and use it in GitHub Desktop.
Save benshimmin/9768356 to your computer and use it in GitHub Desktop.
Breaking out of loops with Underscore
// If you've ever written code like this:
var result;
_.each(somethings, function(something) {
if (something === particularSomething) {
result = something;
}
});
// ... and then thought, "If I were writing this as a `for` loop, I'd put in
// a `break` when I'd got my match..." then what you're looking for is this:
var result;
_.every(somethings, function(something) {
var breaker;
if (breaker = something === particularSomething) {
result = something;
}
return !breaker;
});
// There is, of course, a native `Array.every` too.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment