Introduction
When starting with JavaScript, I stumbled upon this forEach loop method, and I felt excited. And here's what happened, I thought I could 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 want to admit that I am one of those developers who occasionally fail to read the documentation. 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 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 expecting 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 of this article.
- What is JavaScript forEach?
- Why can't we use the break, continue, or return within forEach?
- Other alternatives to forEach when you want to break
What is JavaScript forEach?
The JavaScript forEach method allows you to run a function/method for every element inside the array.
Syntax
//the syntax
[].forEach(function(item, index, array){
//do your stuff here...
});
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 array, respectively.
Now, let's increase the difficulty level of the example and use the 3 arguments.
<script>
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);
</script>
Output
Why can't we use the break, continue, or return within forEach?
Let's start with an example,
<script>
let amounts=[1.25,2.25,3.25,4.25];
amounts.forEach((item)=>{
if(item===3.25){
break;
}
});
</script>
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.
The official MDN(Mozilla Developer Network ) documentation says,
"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
JavaScript for Loop
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.
<script>
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);
}
</script>
Output
JavaScript every() Function
Using every() function tests all elements in the array, and all elements must pass the test.
Syntax
<script>
[].every((element, index, array) => {
//do your test here
return true;
});
</script>
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.
<script>
['apple', 'mango', 'avocado', 'dragon fruit'].every(
(element, index, array) => {
console.log(
`${element}===${array[index]}is equals to ${
element === array[index]
}`
);
return true;
}
);
</script>
Output
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 meets.
<script>
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');
}
</script>
Output
Let's take an example
JavaScript some() Function
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 passes a certain condition, it will return out of the Loop.
The syntax,
<script>
[].some(function (element, index, array) {
//do something here
});
</script>
Let's make a good example.
<script>
const fruitCollection = [
'apple',
'mango',
'avocado',
'dragon fruit',
'hamburger',
'banana',
];
fruitCollection.some((element) => {
console.log(element);
if (element === 'mango') {
return true;
}
return false;
});
</script>
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!