Alihan Koç
Alihan Koç

Reputation: 1094

How to check if a condition in foreach function matched in Javascript?

I have a Javascript function. I check a condition for every element in an array and if there is a match, I stop the loop. For example:

var myarray = [5,6,7,8,9,10];
myarray.forEach(function(element){
  if(element == 8)
    break;
});

//myother functions here..

Everything seems okay so far. But after breaking the loop, my other functions continues to run.

If a match happens in foreach function, i don't want to continue to next functions, if nothing match it can continue.

How can I do this?

Upvotes: 1

Views: 7000

Answers (1)

niklas
niklas

Reputation: 3011

For example you could use (version without functions)

var myarray = [5,6,7,8,9,10];
var found = false;
myarray.forEach(function(element){
  if(element == 8)
    found = true;
});

if (!found) {
  //myother functions here..
}

Or if you are just looking for a single element

if (myarray.indexOf(8) == -1) {
  //myother functions here..
}

Upvotes: 3

Related Questions