Go to "next" iteration in JavaScript forEach loop

JavascriptForeach

Javascript Problem Overview


How do I go to the next iteration of a JavaScript Array.forEach() loop?

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);
});

MDN docs only mention breaking out of the loop entirely, not moving to next iteration.

Javascript Solutions


Solution 1 - Javascript

You can simply return if you want to skip the current iteration.

Since you're in a function, if you return before doing anything else, then you have effectively skipped execution of the code below the return statement.

Solution 2 - Javascript

JavaScript's forEach works a bit different from how one might be used to from other languages for each loops. If reading on the MDN, it says that a function is executed for each of the elements in the array, in ascending order. To continue to the next element, that is, run the next function, you can simply return the current function without having it do any computation.

Adding a return and it will go to the next run of the loop:

var myArr = [1,2,3,4];

myArr.forEach(function(elem){
  if (elem === 3) {
    return;
  }

  console.log(elem);
});

Output: 1, 2, 4

Solution 3 - Javascript

just return true inside 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);
});

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDon PView Question on Stackoverflow
Solution 1 - JavascriptridView Answer on Stackoverflow
Solution 2 - JavascriptChristoffer KarlssonView Answer on Stackoverflow
Solution 3 - JavascriptdimshikView Answer on Stackoverflow