Javascript – Break forEach loop

One way to break a forEach loop in Javascript is to make use of the try and catch.

var BreakException= {};
          
try {
  [1,2,3,4,5].forEach(function(val) {
    if (val == 3) {
      throw BreakException;
    } else {
      console.log(val);
    }
  });
} catch(e) {
  if (e !== BreakException) {
    throw e;
  }
}

// Result: only print 1 and 2.

 

You can also make use of the Array.some or Array.every but it may not work in some browsers. For more information, please refer to the reference below.

Done =)

Reference: StackOverflow – How to short circuit Array.forEach like calling break?

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s