June 9, 2021

How to break out of JavaScript forEach() loop

How to break out of JavaScript forEach() loop

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.

What is a forEach() loop?

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.

Here is a quick syntax sample of what a forEach() loop looks like:

const items = ["apples", "bananas", "pears"];

items.forEach(item => {
  //some code here
  console.log(item.index);
});

Here's a rundown on how the above code works.

  • items is the list you want to iterate over using forEach()
  • item inside forEach() represents the single item inside the list that is passed in. This can be called anything you want – but it is good practice to use the singular version of your list name. For example, if your list name was fruits, your callback is called fruit.
  • using .index will give you the index number of the value of the instance you are currently accessing.

What makes a forEach() loop more special over a normal for() loop?

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:

for(i = 0; i < 10; i++){
  //some code here
}

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:

const items = ["apples", "bananas", "pears"];

for(item = 0; item < items.length; item++){
  //some code here
}

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.

When using a forEach() loop, you can write something like this:

const items = ["apples", "bananas", "pears"];

function printValue(value){
  console.log(value);
}

items.forEach(printValue);

However, if we used a simple for() loop, we might have to write it like this to get the same result:

const items = ["apples", "bananas", "pears"];

function printValue(values, value){
  console.log(values[value]);
}

for(item = 0; item < items.length; item++){
    printValue(items, item);
}

The major difference here is that in forEach() , the actual value is passed in. However, in for(), we only have access to the index of the instance. This means that to get the same result, our printValue() function requires two parameters to be passed in – the list it is iterating over, and the index of the item.

As a result, your function can get messy over time. Rather than just focusing on the data set that you're being passed in, you also have to handle passing in the list where the dataset lives. This means that if the list name changes, you will also have to change the parameters being passed in through.

What if you want to track the index inside a forEach() loop?

In a forEach() loop, you don't need to explicitly add in any additional details to the callback invoked. However, you can add an index tracker parameter inside your actual callback function. All you have to do is add it as an extra parameter after your value.

Here is an example:

const items = ["apples", "bananas", "pears"];

function printValue(value, index){
  console.log(value, index);
}

items.forEach(printValue);

How do you break out of a forEach() loop?

Sometimes, you don't want to loop through every single item inside a list. This might be for the following reason:

  • you are looking for a specific value
  • you have a massive list and don't need every item inside

By default, there is no way you can cancel a forEach() loop. However, one method you can use is to put in a 'fake' loop break – that is, put a conditional around your logic to only execute when the conditions are matched.

For example:

const items = ["apples", "bananas", "pears"];

function printValue(value, index){ 
  if(value != "bananas"){
    console.log(value, index);
  }
 
}

items.forEach(printValue)

You can, however, use break inside a for() loop.  break will stop the iteration when it is called. For example:

const items = ["apples", "bananas", "pears"];

for(const item of items){
  console.log(item);
  if(item == "bananas" ){
    console.log('found a banana!');
    break;
  }
}

However, this only allows for one instance of the condition and doesn't account for subsequent instances that may meet the condition. Using for() isn't the most elegant solution either.

So what are your alternatives?

Alternative to forEach() loop: find() and filter()

If you are looking for a specific item in an array, you can use the find() method. find() is a much more effective and efficient way to search for your specific item in an array.

Here is the JavaScript syntax for it:

const items = ["apples", "bananas", "pears"];

const findBananas = items.find(item => item == "bananas");

console.log(findBananas);

So how does the above code for find() work?

  • items is the list you want to use find() on
  • item is the singular instance inside the array find() is working through
  • item == "bananas" is the conditional

You can also pass in a callback function that takes in the value, index, and array itself for find(). This will give you access to the actual item that's being iterated, the index value, and the actual array that find() is working with.

Here is the syntax example:

const items = ["apples", "bananas", "pears"];

function isBanana(element, index, array){
   if(element == "bananas"){
     return element;
   }else{
     return false; 
   }
}

const findBananas = items.find(isBanana);

console.log(findBananas);

However, find() only targets the first instance it encounters. To find multiple items in an array, you can use the filter() method with include()  for your conditional.

Here is an example of how to use filter() with include() :

const items = ["apples", "bananas", "pears", "bananas"];

const findBanana= items.filter(item => item.includes("bananas"));

console.log(findBanana);

The result will return an array of ["bananas", "bananas"]. This can be useful for information rich lists and more complex datasets.

And that's basically it for this piece. Thank you for reading and I hope you've found it useful as a starting reference point.