var BreakException = {};
try {
[1, 2, 3].forEach(function(el) {
console.log(el);
if (el === 2) throw BreakException;
});
} catch (e) {
if (e !== BreakException) throw e;
}
The for…of loop would be the preferred solution to this problem. It provides clean easy to read syntax and also lets us use break once again.
let data = [
{name: 'Rick'},{name: 'Steph'},{name: 'Bob'}
]
for (let obj of data) {
console.log(obj.name)
if (obj.name === 'Steph') break;
//Use some instead
[1, 2, 3].some(function(el) {
console.log(el);
return el === 2;
});
/* use for...of instead
Officially, there is no proper way to break out of a forEach loop in javascript.
Using the familiar break syntax will throw an error
If breaking the loop is something you really need,
it would be best to consider using a traditional loop. */