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?