Skip to content

Instantly share code, notes, and snippets.

@wilmoore
Last active February 22, 2017 05:27
Show Gist options
  • Save wilmoore/4478487 to your computer and use it in GitHub Desktop.
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.
/**
* 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;
});
@dsernst
Copy link

dsernst commented Sep 2, 2015

Thanks 👍

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment