How to break forEach in JavaScript
In this article, you will learn about how to break 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 stop the loop when the value is 3 in your numbers array. How will you do this? You simply add a break in that loop. But there’s an issue that will create when you are going to use break in a forEach loop. Let’s see the issue first:
const numbers = [1,2,3,4,5]
numbers.forEach(num => {
if (num === 3) {
// SyntaxError: Unsyntactic break.
break;
}
})
You will simply get an Unsyntactic 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 use a break on it.
Though forEach never lets you perform this type of action if you are really bound to use break in forEach loop then there’s some alternative for it.To break in forEach loop you can simply use every() instead of using forEach(). every() is as similar as forEach(). See the code below:
const numbers = [1,2,3,4,5]
numbers.every(num => {
if (num === 3) {
return false;
}
console.log(num)
return true
})
//output : 1, 2
Note: You have to keep one thing your mind that while using every() you have to return true at the end otherwise it will stop the loop and you may not get the desired output.
If every() looks complex to you then you may use numbers.slice() and skip those unwanted values that you are not want to see. For example
const numbers = [1,2,3,4,5]
numbers.slice(0,numbers.findIndex(num => num === 3).forEach(num => {
console.log(num)
})
//output : 1, 2
There’s an another tricky solution for this situation. You can simple use a flag variable. Let me show that to you in the below code :
const numbers = [1,2,3,4,5]
let flag = false
numbers.forEach(num => {
if(flag){
return
}
if(num === 3){
flag = true
return
}
console.log(num)
})
// Output : 1, 2
Important: Always try to avoid forEach() loop in a situation where you need to use break statement over an array and try to use traditional for loop or for of loop instead of using forEach() loop.