One way to break a forEach loop in Javascript is to make use of the try and catch.
var BreakException= {};
try {
[1,2,3,4,5].forEach(function(val) {
if (val == 3) {
throw BreakException;
} else {
console.log(val);
}
});
} catch(e) {
if (e !== BreakException) {
throw e;
}
}
// Result: only print 1 and 2.
You can also make use of the Array.some or Array.every but it may not work in some browsers. For more information, please refer to the reference below.
Done =)
Reference: StackOverflow – How to short circuit Array.forEach like calling break?
