How to break when looping an array in Javascript

Benjamin Cherion
Jul 21, 2016 · 2 min read

There are different ways to break an array: some are good, some are bad. Obviously I will just focus on the good ones !

I’ll cover in this article different loops:

  1. for
  2. for-of (ES2015)
  3. forEach()
  4. every()
  5. some()

1. for

With a for loop, use “break”:

or if you prefer, let’s use a function (return false):

2. for-of (ES2015)

With a for-of loop, use “break”, as well:

or if you prefer, let’s use a function (return false):

3. forEach()

Remember this : YOU CAN’T BREAK A FOREACH IN A GOOD WAY ! (but there are good alternatives …).

4. every()

The every() method will test all elements of an array (all elements must pass the test). It is a good alternative to replace forEach for breaking an array:

5. some()

The some() method will test all elements of an array (only one element must pass the test). It is also a good alternative to replace forEach for breaking an array: