JavaScript —How to break statement in an array map method
2 min readOct 4, 2022
Array .map and .forEach are designed to never be stopped. Therefore, you cannot break out of the loop when using those methods. Here are 3 alternative solutions.
Method #1 — emulating a ‘break’
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;
}
});
Method #2— ‘some’ method
Using .some
you can get iteration functionally similar to .forEach
, map
or for
loop but with the ability to break
through return
instead.
range.some(function(rangeValue , i) {
if (rangeValue <= enteredValue) {
percentages.push(100);
enteredValue = enteredValue - rangeValue;
return true
}
percentages.push(enteredValue * 100 / (rangeValue));
});
Method #3— ‘for loop’
const percentages = [];
let enteredValue = parseInt(event.target.value, 10);
for(const range of ranges) {
percentages.push(Math.min(100, (enteredValue / range) * 100));
enteredValue -= range;
if(enteredValue <= 0) break;
}