There's a few ways of breaking a forEach()
loop in JS.
every()
instead of forEach()
if possible:[1, 2, 3, 4, 5].every(val => {
if (val > 4) {
return false
}
return true
})
Loop is stopped if val > 4
.
return false
equals to break
return true
equals to continue
let terminate = false
[1, 2, 3, 4, 5].forEach(val => {
if (terminate) {
return
}
if (val > 4) {
terminate = true
return
}
})
It's clunky, but it works 😆
for
loop, where you can use break
and continue
statements.