Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you break a forEach loop?

There is no way to stop or break a forEach() loop other than by throwing an exception. If you need such behavior, the forEach() method is the wrong tool.

Can you return from a forEach loop?

You can't make JavaScript's forEach() function return a custom value. Using return in a forEach() is equivalent to a continue in a conventional loop.

Does continue work in forEach?

To continue in a JavaScript forEach loop you can't use the continue statement because you will get an error. Instead you will need to use the return statement in place of the continue statement because it will act in the same way when using a forEach because you pass in a callback into the forEach statement.


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.


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


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