forEach() loops in JavaScript are fun to use – until you need to get out of them. Here is a short guide on how forEach() works, how to break out of

How to break out of JavaScript forEach() loop

submited by
Style Pass
2021-06-09 11:00:11

forEach() loops in JavaScript are fun to use – until you need to get out of them. Here is a short guide on how forEach() works, how to break out of a forEach() loop, and what the alternatives to a forEach() loop are.

A forEach() loop is a type of array method that runs a callback function on each item in an array. This means that forEach() can only be used on things that are iterable like Arrays, Sets, and Maps.

A forEach() loop accepts a callback function while a normal for() loop does not. Here is a quick refresher of what a for() loop looks like:

A simple for() loop will keep repeating the code inside until the conditions of the second for parameter is met. So, for example, to iterate over the same array in the above example, we can write it like this:

However, as your code grows, this can be quite cumbersome to maintain. The code inside your for() loop also becomes tightly coupled with it, reducing its re-usability.

Leave a Comment