Signup/Sign In
Ask Question
Not satisfied by the Answer? Still looking for a better solution?

Short circuit Array.forEach like calling break

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


How can I achieve this utilising the latest forEach way in JavaScript? I've tried return;, return false; and break. break crashes and return does nothing but continue iteration.
by

2 Answers

aashaykumar
You can use every method:

[1,2,3].every(function(el) {
return !(el === 1);
});

ES6

[1,2,3].every( el => el !== 1 )
for old browser support use:

if (!Array.prototype.every)
{
Array.prototype.every = function(fun /, thisp/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();

var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this &&
!fun.call(thisp, this[i], i, this))
return false;
}

return true;
};
}
RoliMishra
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

[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.

Login / Signup to Answer the Question.