Last updated on Sep 24, 2020 by Suraj Sharma
In this tutorial, you will learn how you can break out of the Array.foreach()
method in JavaScript
The break
statement is being used to stop a for
loop or a for...of
loop in JavaScript.
const array = [1,2,3,4,5];
for(let i=0; i<array.length; i++) {
if (i>=3) {
break;
}
console.log(array[i])
}
// 1
// 2
// 3
However, the break
statement does not work inside the foreach because of the callback function, it throws Uncaught SyntaxError: Illegal break statement
error
const array = [1,2,3,4,5];
array.forEach(num=>{
if (num >= 3) {
break;
};
console.log(num)
})
// Uncaught SyntaxError: Illegal break statement
To break out of the forEach()
method we have to write the return
statement instead of the break
statement.
const array = [1,2,3,4,5];
array.forEach(num=>{
if (num >= 3) {
return;
};
console.log(num)
})
// 1
// 2
Related Solutions
Rate this post
Suraj Sharma is the founder of Future Gen AI Services. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.