Created
March 25, 2014 18:39
-
-
Save benshimmin/9768356 to your computer and use it in GitHub Desktop.
Breaking out of loops with Underscore
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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