How can I break (similar to the break statement) from an implicit loop on an array?
The Array.prototype.map, Array.prototype.forEach, etc. functions imply a loop over the elements of the array. I want to conditionally break that loop early.
This contrived example:
const colours = ["red", "orange", "yellow", "green", "blue", "violet"];
colours.map(item => {
if (item.startsWith("y")) {
console.log("The yessiest colour!");
break;
}
});
causes a SyntaxError: unlabeled break must be inside loop or switch.
How can I break the loop the same way a break statement would?
You can't do it using a regular way. You can emulate the break behaviour by remembering whether the loop is "broken". The lack of this solution is that the loop actually continues (though the iteration logic is skipped).
let isBroken = false;
colours.map(item => {
if (isBroken) {
return;
}
if (item.startsWith("y")) {
console.log("The yessiest colour!");
isBroken = true;
return;
}
});
The best solution for your example is to use a plain for loop.
for (colour of colours) {
if (colour.startsWith("y")) {
console.log("The yessiest colour!");
break;
}
}
Also you can use a dirty way to actually stop a map loop.
colours.map((item, index, array) => {
if (item.startsWith("y")) {
console.log("The yessiest colour!");
array.splice(0, index);
}
});
// The colours array will be modified after this loop
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With