Breaking Out Of .forEach() Loop

Breaking Out Of .forEach() Loop

JavaScript Insider

We all know breaking out of for_loop or while_loop even for_of.. in javascript or any other language, we use the Break statement. But in case of forEach() it's not possible.

We won't be talking about forEach() in detail in this blog instead looking at some techniques or methods to break out of it.

Throwing Exception

Throwing an exception is good method which can be used to break a forEach() loop since program shift it's control to catch block after an exception is thrown. But If this exception is not handled carefully it can cause potential bugs in an application.

Here finally block can also be used if such a functionality is required.

Skipping Elements

Here we iterate through all elements but we skip certain elements using the return statement in a given conditional(if block).

Using Array: length Property

During looping if we can change the array length(array.length = 0) than we can successfully breakout of forEach loop. But this can be dangerous since mutating the given object/array is considered dangerous practice. Hence making a deep copy of the array first and then applying the given method is considered more ideal.

Using alternatives

.some()

Using some() we can create a break situation if we return a true value.

.every()

Using every() we can create a break situation if we return a false value when the condition is reached, but other wise always return a truthy value.

That's it for today geeks!