What is forEach?
The forEach method allows you to run a function/method for every element inside the array.
The syntax,
-
- [].forEach(function(item, index, array){
-
- });
For example, let's iterate over a fruit collection and print the value in the console. - ["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.
- let amounts = [1.25, 2.25, 3.25, 4.25];
-
- const showAmountCollection = (item, index, array) => {
- console.log("Amounts to $" + item);
- console.log("Amount collection position of amount[" + index + "] == " + array[index]);
- };
-
- amounts.forEach(showAmountCollection);
Output
Why can't we use the break, continue, or return within forEach?
Let's start with an example,
- let amounts = [1.25, 2.25, 3.25, 4.25];
- amounts.forEach((item) => {
-
- if(item === 3.25){
- break;
- }
- });
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.
- let array = [1.25, 2.25, 3.25, 4.25];
-
- for (let index = 0; index < array.length; index++) {
- const element = array[index];
- if(element >= 3){
- break;
- }
- console.log(element);
- }
Output
every
Using every() function tests all elements in the array and all elements must pass the test.
The syntax,
- [].every((element, index, array) => {
-
-
-
- return true;
- });
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.
- ["apple", "mango", "avocado", "dragon fruit"].every((element, index, array) => {
-
- console.log(`${element} === ${array[index]} is equals to ${element === array[index]}`);
-
- return true;
- });
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.
- const fruitCollection = ["apple", "mango", "avocado", "dragon fruit", "hamburger", "banana"];
-
- const isEverythingAFruit = (element) => {
-
- console.log(element);
-
- if(element === "hamburger"){
- return false;
- }
- else{
- return true;
- }
- }
-
- let result = fruitCollection.every(isEverythingAFruit);
-
- if(!result){
- console.log("Not everything in the collection is a fruit");
- }
Output
Enhanced example,
- const fruitCollection = ["apple", "mango", "avocado", "dragon fruit", "hamburger", "banana"];
-
- const isEverythingAFruit = (element) => element !== "hamburger";
-
- let result = fruitCollection.every(isEverythingAFruit);
-
- if(!result){
- console.log("Not everything in the collection is a fruit");
- }
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,
- [].some(function(element, index, array) {
-
- });
Let's make a good example.
- const fruitCollection = ["apple", "mango", "avocado", "dragon fruit", "hamburger", "banana"];
-
- fruitCollection.some((element) => {
-
- console.log(element);
-
- if(element === "mango"){
- return true;
- }
-
- return false;
- });
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
I hope you have enjoyed this article, as I have enjoyed writing it. Until next time, happy programming!
References