Problem
How do I continue a JavaScript Array.forEach() loop to the next iteration?
For example:
var myArr = [1, 2, 3, 4];
myArr.forEach(function(elem){
if (elem === 3) {
// Go to "next" iteration. Or "continue" to next iteration...
}
console.log(elem);
});
The MDN documentation only mentions breaking out of the loop and not progressing to the next iteration.
Asked by Don P
Solution #1
If you wish to skip the current iteration, simply return.
Because you’re in a function, if you return before doing anything else, the code below the return statement is effectively skipped.
Answered by rid
Solution #2
The forEach loop in JavaScript works a little differently than other languages’ forEach loops. According to the MDN, a function is run for each entry in the array in ascending order. You can just return the current function without having it complete any computation to go to the next element, i.e. run the next function.
It will go to the next execution of the loop if you add a return:
1, 2, 4 are the outputs.
Answered by Christoffer Karlsson
Solution #3
Simply return true from your if statement.
var myArr = [1,2,3,4];
myArr.forEach(function(elem){
if (elem === 3) {
return true;
// Go to "next" iteration. Or "continue" to next iteration...
}
console.log(elem);
});
Answered by dimshik
Post is based on https://stackoverflow.com/questions/31399411/go-to-next-iteration-in-javascript-foreach-loop