[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.
[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.
If you would like to use Dean Edward's suggestion and throw the StopIteration error to break out of the loop without having to catch the error, you can use the following the function (originally from here):
The above code will give you the ability to run code such as the following without having to do your own try-catch clauses:
One important thing to remember is that this will only update the Array.prototype.forEach function if it already exists. If it doesn't exist already, it will not modify the it.
If you don't need to access your array after iteration you can bail out by setting the array's length to 0. If you do still need it after your iteration you could clone it using slice..
Or with a clone:
Which is a far better solution then throwing random errors in your code.
you can follow the code below which works for me:
You can use every method:
ES6
for old browser support use:
more details here.
I prefer to use
for in
for in
works much likeforEach
, and you can add return to exit function inside. Better performance too.Use the
array.prototype.every
function, which provide you the utility to break the looping. See example here Javascript documentation on Mozilla developer network