Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Short circuit Array.forEach like calling break

[1,2,3].forEach(function(el) {     if(el === 1) break; }); 

How can I do this using the new forEach method in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.

like image 422
Scott Klarenbach Avatar asked Apr 14 '10 21:04

Scott Klarenbach


People also ask

Can you break array forEach?

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.

Does forEach support break?

Note : There is no way to stop or break a forEach loop. The solution is to use Array.

What is break in forEach loop?

break crashes and return does nothing but continue iteration. It is worth noting that while return does indeed continue the iteration, it will skip any code that comes after it in the block. Take this code for instance: [1,2,3]. forEach(function(el) { if(el === 2) { console.

Does forEach return break?

return doesn't break a loop, the break does! Interestingly the behavior of the example is much different if you alter line 2 and assign the array to a variable first like: var r = [1, 2, 3, 4, 5]; r. forEach(function (n) { . In this case it will break out of the loop.


2 Answers

There's no built-in ability to break in forEach. To interrupt execution you would have to throw an exception of some sort. eg.

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

JavaScript exceptions aren't terribly pretty. A traditional for loop might be more appropriate if you really need to break inside it.

Use Array#some

Instead, use Array#some:

[1, 2, 3].some(function(el) {    console.log(el);    return el === 2;  });

This works because some returns true as soon as any of the callbacks, executed in array order, return true, short-circuiting the execution of the rest.

some, its inverse every (which will stop on a return false), and forEach are all ECMAScript Fifth Edition methods which will need to be added to the Array.prototype on browsers where they're missing.

like image 186
bobince Avatar answered Sep 22 '22 00:09

bobince


There is now an even better way to do this in ECMAScript2015 (aka ES6) using the new for of loop. For example, this code does not print the array elements after the number 5:

let arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];  for (let el of arr) {    console.log(el);    if (el === 5) {      break;    }  }

From the docs:

Both for...in and for...of statements iterate over something. The main difference between them is in what they iterate over. The for...in statement iterates over the enumerable properties of an object, in original insertion order. The for...of statement iterates over data that iterable object defines to be iterated over.

Need the index in the iteration? You can use Array.entries():

for (const [index, el] of arr.entries()) {   if ( index === 5 ) break; } 
like image 43
canac Avatar answered Sep 20 '22 00:09

canac