Break Out from the foreach loop in JS

Nitish Thakur
2 min readMay 2, 2021

Things which you might have not known about the “forEach” loop

1. `return` statement Doesn’t stop the loop

if you think the below code only prints “1,2,3” you are wrong

the reason for this behaviour is that we are passing a callback function in our “foreach” function, which behaves like a normal function and is appliead to each element no matter if we “return” from one.

2. `break` statement Don’t work

do you think “foreach” loop break when equals to 3 ?

The above code will throw an exception

Uncaught SyntaxError: Illegal break statement

This is because , technically the break not inside a loop.

3.`Continue` statement would not work as well

Do you think this code only print “1, 2, 4 ” ?

No, You are wrong. You would end with the following exception:

Uncaught SyntaxError: Illegal continue statement: no surrounding iteration statement

Yes! The continue statement is not executing inside a loop, similar to the break incident mentioned above.

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

1. for()

The “for” loop is probably one of the first mechanisms you learned about when diving into javascript.

With a for loop, use “break”:

// Output: 1 2

2. every()

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

3. some()

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

That was it! Hope you learned something new today.

--

--