How to break when looping an array in Javascript

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()

With a for loop, use “break”:

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

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

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

This was me trying to break a forEach()

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

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:

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:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store