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?
Array#mapis not designed for iteration with side effects (and must not be used for that purpose), it cannot be stopped.Array#forEachcannot be stopped either though. If you need to find something you need to useArray#indexOforArray#findor any other lookup method.fororwhileor, as @zerkms suggested, you could search for your item without iterating at all.forloop with a counter.