While discussing “javascript foreach continue”, in JavaScript’s forEach() function, you cannot use the continue statement, mainly for two reasons:
- JS Array.forEach() method takes a callback function as an argument and executes the provided
callbackFn
function for each element in an array in ascending-index order. - The JS continue statement is valid only within a loop, not in a function.
However, there are only two alternatives available while using the continue statement within the forEach() function. The number one approach is to use return
in a forEach()
callback function. And the second option is to filter out the unwanted values before executing the forEach() function. In this article, we are going to discuss both alternatives in more detail. So bear with us.
Table of Contents
What is the problem with using “JavaScript foreach Continue”?
As mentioned earlier, we are unable to use the continue statement within the JS forEach() function because the continue statement is only valid for pure loops. ForEach() is not a pure loop; rather, it is a JavaScript array method.
Let’s now examine the issue using the example below:
<script>
var array=[1,2,3,4,5];
// trying to use javascript foreach continue
array.forEach((value) => {
if (value === 2) {
// SyntaxError: continue must be inside loop
// Jump target cannot cross function boundary.javascript
continue;
}
// Execute rest of the code upon next iteration
console.log(value);
});
</script>
So what do we get from using JavaScript forEach continue statement all together?
SyntaxError: Illegal continue statement: no surrounding iteration statement.
Or,
SyntaxError: continue must be inside loop
Or,
SyntaxError: Illegal continue statement: ‘label’ does not denote an iteration statement.
Or,
SyntaxError: ‘continue’ is only valid inside a loop statement.
Or,
SyntaxError: Cannot continue to the label ‘label’ as it is not targeting a loop.
So these are the common error messages that you will encounter from different browsers or code editors.
Don’t worry, there are solutions that we are going to discuss now:
No. 1: Use Conditional Return Instead of JavaScript forEach Continue
Using return in a forEach() callback is equivalent to the JavaScript continue statement in a pure for loop. Using conditional return, you are able to skip unwanted executions like the continue statement.
<script>
const array = [10,20,30,40,50];
array.forEach((oItem) => {
if (oItem > 30) return;
// javascript foreach continue
// continue for 40 and 50.
// instead of continue we are using return
console.log('Iterating array item: '+oItem); // 10, 20, 30
});
</script>
Output: JavaScript foreach Continue Alternative
So here the forEach() function iterates for 10, 20, and 30 but skips 40 and 50. By using the return statement, we achieved a continuation-like execution pattern in the above code without using the exact JS continue statement.
No. 2: Filter Out Unwanted Values
Though our recommendation is to use a conditional return instead of continuing, you can achieve the same execution pattern using the array filter method.
What if you filter out the unwanted values from an array before executing the forEach() function? You don’t need to think about the value. You just do what you want to do with the values, as all are relevant now and will surely work as an alternative to the JS continue statement.
<script>
const array = [10,20,30,40,50];
// javascript foreach continue
// filterout 40, 50 first using array filter method
array.filter(x => x<=30).forEach(x => {
console.log('Iterating array item: '+x);
});
</script>
Output
So here we find all array elements upon using the filter() method. So that we don’t need to check the array value again within the forEach() function.
The array filter() method is a very strong method, and you can use it to apply every logic that you may use for a “loop continue statement”. So think of it as a complete alternative.
Conclusion
We hope that, upon reading the article, you understood that JavaScript foreach Continue does not work like a pure loop. As alternatives, we can use either a conditional return statement or filter out all non-required elements from the array before the execution of the forEach() function.
As those two approaches are not really standard approaches, we recommend using a pure loop if you don’t have other issues or stickyness.
So if you are working with heavy arrays and concerned about the performance of your code, then you will need to use a pure for loop or other available loops because it will give you the freedom to use “continue” or “break” statements to avoid visiting unnecessary elements.
FAQs on “JavaScript foreach Continue”
SyntaxError: continue must be inside loop?
The JavaScript exception “continue must be inside loop” occurs only when you are using a continue statement as an outside loop statement. For example, if you think the forEach() function is a loop and you can use the continue statement within it, then you are wrong. forEach() is a function, not a loop.
So place the continue statement only within the pure loop, like for, of, do, while, etc.
But if you are bound to use the continue statement with the forEach() function, then use return as an alternative, like below:
<script>
const array = [];
array.forEach((oItem) => {
// use return as an alternative of JS continue statement
if (expression) return;
// do what you want
});
</script>
Can JavaScript array filter methods take multiple conditions?
Yes, you can use multiple conditions, one by one or all together. Like:
array.filter(x).
filter(y).
count();
Is using several ‘.filter’ calls on a big array bad for performance?
Definitely yes. But it fully depends on the situation. For example:
array.filter(x).filter(y).count();
Array.prototype.filter returns a new array. If the ‘x’ expression can remove the majority of unnecessary elements, then the expression ‘y’ will work on limited data and thus work well; otherwise, it will work badly.
🏋️♂️ Discover Code Blocks From 20+ yrs JS Expert
💥 Asp.net C# Developer
🏆 Solution Architect
👨✈️ Database Administrator
📢 Speaker
🎓 MCTS since 2009
Leave a Reply