JavaScript Array forEach Method And Its Alternatives

Introduction

 
When I was starting with JavaScript, I stumbled upon  this forEach-loop method and I felt excited. And here's what happened, I thought I can use the break or continue keyword within the forEach-loop method, but we cannot. I want to share why we can’t use the break or continue keyword within the forEach-loop method and I'll suggest other alternatives in case you need to break within the loop.
 
I would like to admit that I am one of those developers who occasionally fails to read documentations. Sometimes, once I have seen the syntax and due to excitement, I immediately decide to use it without knowing how it works internally. Then, I happen to know that something works with other programming-languages which may work with what I am currently working on. But it resulted differently from what I was xpecting in the first place. Thus, I ended up having a better understanding of the JavaScript forEach-loop method.

Enough of my story, here are the contents for this article:
  • What is forEach?
  • Why we can't use the break, continue, or return within forEach?
  • Other alternatives to forEach when you want to break

    • for
    • every
    • some

What is forEach?

 
The forEach method allows you to run a function/method for every element inside the array. 
 
The syntax,
  1. //the syntax   
  2. [].forEach(function(item, index, array){  
  3.     //do your stuff here...  
  4. });  
For example, let's iterate over a fruit collection and print the value in the console. 
  1. ["apple""mango""avocado""dragon fruit"].forEach(console.log);  
Output
 
 
Looks easy doesn't it? It prints the item, index, and the array respectively. 
 
Now, let's increase the difficulty level of the example and use the 3 arguments. 
  1. let amounts = [1.25, 2.25, 3.25, 4.25];  
  2.   
  3. const showAmountCollection = (item, index, array) => {  
  4.     console.log("Amounts to $" + item);  
  5.     console.log("Amount collection position of amount[" + index + "] == " + array[index]);  
  6. };  
  7.   
  8. amounts.forEach(showAmountCollection);  
Output
 
 

Why can't we use the break, continue, or return within forEach?

 
Let's start with an example,
  1. let amounts = [1.25, 2.25, 3.25, 4.25];  
  2. amounts.forEach((item) => {  
  3.   
  4.     if(item === 3.25){  
  5.         break;  
  6.     }  
  7. });  
Output
 
 
Coming from a C# programming-language background, I was telling myself that it should work. As a result, I decided to dig deeper to understand the forEach method. Let me show what I have learned. 
 
 
"There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool." 
 
The reason is the forEach-loop method has a callback function applied to every element within the array. Thus, the callback function needs to finish itself regardless if it has a jump statement within the function such as continue or break.
 

Other alternatives to forEach when you want to break

 
for
 
If you have been programming for a while or are a newbie or somewhere intermediate, you might know this already. But, it won't hurt.
 
The JavaScript for-loop does accept jump statements within its block statement. 
  1. let array = [1.25, 2.25, 3.25, 4.25];  
  2.   
  3. for (let index = 0; index < array.length; index++) {  
  4.     const element = array[index];  
  5.     if(element >= 3){  
  6.         break;  
  7.     }  
  8.     console.log(element);  
  9. }  
Output
 
 
every
 
Using every() function tests all elements in the array and all elements must pass the test.
 
The syntax,
  1. [].every((element, index, array) => {  
  2.   
  3.     //do your test here  
  4.   
  5.     return true;  
  6. });  
Let's try to have an example that iterates over an array but doesn't have any test yet. But, we won't forget to return a boolean.
  1. ["apple""mango""avocado""dragon fruit"].every((element, index, array) => {  
  2.   
  3.     console.log(`${element} === ${array[index]} is equals to ${element === array[index]}`);  
  4.   
  5.     return true;  
  6. });  
The every() function is a good alternative to forEach, let us see an example with a test implementation, and then let's return out of the every() function when a certain condition meet.
  1. const fruitCollection = ["apple""mango""avocado""dragon fruit""hamburger""banana"];  
  2.   
  3. const isEverythingAFruit = (element) => {  
  4.   
  5.     console.log(element);  
  6.   
  7.     if(element === "hamburger"){  
  8.         return false;  
  9.     }  
  10.     else{  
  11.         return true;  
  12.     }  
  13. }  
  14.   
  15. let result = fruitCollection.every(isEverythingAFruit);  
  16.   
  17. if(!result){  
  18.     console.log("Not everything in the collection is a fruit");  
  19. }  
Output
 
 
Enhanced example,
  1. const fruitCollection = ["apple""mango""avocado""dragon fruit""hamburger""banana"];  
  2.   
  3. const isEverythingAFruit = (element) => element !== "hamburger";  
  4.   
  5. let result = fruitCollection.every(isEverythingAFruit);  
  6.   
  7. if(!result){  
  8.     console.log("Not everything in the collection is a fruit");  
  9. }   
some
 
The some() function will test all elements of an array but only one element must pass the test thus making it a good candidate as an alternative to forEach. Once it passed a certain condition it will return out of the loop.
 
The syntax,
  1. [].some(function(element, index, array) {  
  2.           //do something here  
  3.  });  
Let's make a good example. 
  1. const fruitCollection = ["apple""mango""avocado""dragon fruit""hamburger""banana"];  
  2.   
  3. fruitCollection.some((element) => {   
  4.       
  5.     console.log(element);  
  6.   
  7.     if(element === "mango"){  
  8.         return true;  
  9.     }  
  10.       
  11.     return false;  
  12. });  
The given example above breaks out of the loop when it returns true. Thus, it didn't check all of the elements in the array.
 
Output
 
 

Summary

 
In this article, we have discussed the following, 
  • What is forEach?
  • Why can't we use the break, continue, or return within forEach?
  • Other alternatives to forEach when you want to break
    • for
    • every
    • some
I hope you have enjoyed this article, as I have enjoyed writing it. Until next time, happy programming! Kendo UI jQuery Validator 
 
References