Breaking out of forEach() loop

Published 
JavaScript

There's a few ways of breaking a forEach() loop in JS.

  1. Using 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

  1. Using a local variable as flag:

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 😆

Please note

Using just return is the same as "return undefined".
  1. Or just switch to for loop, where you can use break and continue statements.