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; }
Run code snippetExpand snippet
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; });
Run code snippetExpand snippet
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.