Short circuit Array.forEach like calling break
arrays, foreach, javascript
Solution
There's no built-in ability to `break` in `forEach`. To interrupt execution you would have to throw an exception of some sort. eg.
var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
JavaScript exceptions aren't terribly pretty. A traditional `for` loop might be more appropriate if you really need to `break` inside it.
Use `Array#some`
Instead, use `Array#some`:
[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});
This works because `some` returns `true` as soon as any of the callbacks, executed in array order, return `true`, short-circuiting the execution of the rest.
`some`, its inverse `every` (which will stop on a `return false`), and `forEach` are all ECMAScript Fifth Edition methods which will need to be added to the `Array.prototype` on browsers where they're missing.
Use `Array#every`
[1, 2, 3].every(v => {
if (v > 2) {
return false // "break"
}
console.log(v);
return true // must return true if doesn't break
});
Problem
``` [1,2,3].forEach(function(el) { if(el === 1) break; }); ``` How can I do this using the new `forEach` method in JavaScript? I've tried `return;`, `return false;` and `break`. `break` crashes and `return` does nothing but continue iteration.