JavaScript Break foreach
//break out of for loop
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
}
Grepper
//break out of for loop
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
}
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;