[javascript] Go to "next" iteration in JavaScript forEach loop

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.

This question is related to javascript foreach

The answer is


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

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:

_x000D_
_x000D_
var myArr = [1,2,3,4];_x000D_
_x000D_
myArr.forEach(function(elem){_x000D_
  if (elem === 3) {_x000D_
    return;_x000D_
  }_x000D_
_x000D_
  console.log(elem);_x000D_
});
_x000D_
_x000D_
_x000D_

Output: 1, 2, 4