JavaScript forEach() is a function rather than a loop, if we use the continue statement then it throws errors. You can simply return
if you want to skip the current iteration.
Note: Use for/of loops to iterate through an array unless you have a good reason not to. However, if you find yourself stuck with a forEach() and need to skip to the next iteration use return.
JavaScript forEach continue example
Simple example code.
<!DOCTYPE html>
<html>
<head>
<script>
var arr = [1, 2, 3, 4, 5]
arr.forEach(v => {
if (v % 2 !== 0) {
continue;
}
});
</script>
</head>
</html>
Output: Uncaught SyntaxError: continue must be inside the loop
Go to “next” iteration in JavaScript forEach loop
Since you’re in a function, if you return
before doing anything else, then you have effectively skipped the execution of the code below the return
statement.
<script>
var myArr = [1,2,3,4];
myArr.forEach(function(elem){
if (elem === 3) {
return;
}
console.log(elem);
});
</script>
Output: 1 2 4
Or adding a return and it will go to the next run of the loop:
// Prints "2, 4"
[1, 2, 3, 4, 5].forEach(v => {
if (v % 2 !== 0) {
return;
}
console.log(v);
});
Do comment if you have any doubts or suggestions on this JS forEach code.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version