Go to "next" iteration in JavaScript forEach loop

Don P picture Don P · Jul 14, 2015 · Viewed 160.3k times · Source

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.

Answer

rid picture rid · Jul 14, 2015

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.