How to continue forEach in javaScript
In this article, you will learn about how to continue forEach loop in javaScript.
In JavaScript, forEach loop is considered as an array method that executes a custom callback function on each item in an array. You can use forEach loop only on the array. Let’s see a forEach loops example first:
Suppose you have a numbers array that contains 1 to 5 numbers. How you will print the value in forEach loop. Let me show that to you:
const numbers = [1,2,3,4,5]
numbers.forEach(num => {
console.log(num)
})
//output : 1, 2, 3, 4, 5
Let’s assume, you want to do something more. You want to skip those values that are even in your numbers array. How will you do this? You simply add continue in that loop. But there’s an issue that will create when you are going to use continue in a forEach loop. Let’s see the issue first:
const numbers = [1,2,3,4,5]
numbers.forEach(num => {
if (num % 2 === 0) {
// SyntaxError: Illegal continue statement: no surrounding iteration statement
continue;
}
})
You will simply get a Syntax Error like that. This is happening because forEach loop works more like a function rather than a loop. That is why you can not perform continue on it.
But if you really need to use continue in forEach loop then there’s an alternative for it. To continue in forEach loop you can simply use return. See the code below:
const numbers = [1,2,3,4,5]
numbers.forEach(num => {
if (num % 2 === 0) {
return;
}
console.log(num)
})
//output : 1, 3, 5
Though you can get your desired output by using return there is a more efficient way to do so. You can simply filter out the unwanted values by using the filter() method. Example :
const numbers = [1,2,3,4,5]
numbers.filter(num => num % 2 !== 0).forEach(num => {
console.log(num)
})
//output : 1, 3, 5
This is how you can use continue in a javaScript forEach loop.