Last active
February 22, 2017 05:27
-
-
Save wilmoore/4478487 to your computer and use it in GitHub Desktop.
Array iteration early exit options -- best options are lodash.forEach or Array#some.
This file contains 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
/** | |
* Use `Array#some` when it is convenient to exit on truthy return values | |
* Use `lodash.forEach` when it is convenient to exit on false (you can cast if necessary with `!!`) | |
*/ | |
var _ = require('lodash'); | |
var numbers = [1, 2, 3, 4, 5, 6]; | |
console.log('Array#forEach (result not as expected)'); | |
numbers.some(function (number) { | |
console.log(number); | |
if (number >= 4) return; | |
}); | |
console.log('Array#some (result as expected)'); | |
numbers.some(function (number) { | |
console.log(number); | |
if (number >= 4) return true; | |
}); | |
console.log('_.forEach (result as expected)'); | |
_.forEach(numbers, function (number) { | |
console.log(number); | |
if (number >= 4) return false; | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Thanks 👍