Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Break the loop of an Array looping function (map, forEach, etc.)

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?

like image 648
bignose Avatar asked Feb 23 '26 01:02

bignose


1 Answers

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
like image 107
Finesse Avatar answered Feb 25 '26 13:02

Finesse