[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.
forEach
return;
return false;
break
return
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; }
548k questions
547k answers
4 comments
86.3k users