The some() and every() Array Methods in JavaScript
In 2009, ECMAScript 5 introduced many new Array methods. Some of them are quite popular, such as indexOf()
, forEach()
, map()
, and filter()
. Others like some()
and every()
, however, seem to be less frequently used, which is why I want to examine those a little closer.
#The Array.prototype.some()
Method
The Array.prototype.some()
method determines whether at least one element of the array matches the given predicate. It only returns false
if none of the array elements match the predicate:
function isNegative(x) {
return x < 0;
}
assert([-10, 0, 10].some(isNegative) === true);
assert([1, 2, 3, 4].some(isNegative) === false);
With the introduction of arrow functions in ECMAScript 2015, we can even inline the predicate function and still maintain readability:
assert([-10, 0, 10].some(x => x < 0) === true);
assert([1, 2, 3, 4].some(x => x < 0) === false);
Note that some()
stops iterating over the array as soon as it finds an element that matches the predicate. In that case, it immediately returns true
without inspecting the remaining elements.
#The Array.prototype.every()
Method
The Array.prototype.every()
method determines whether all elements of the array match the predicate:
assert([-10, 0, 10].every(x => x < 0) === false);
assert([-10, 0, 10].every(x => x >= 0) === false);
assert([1, 2, 3, 4].every(x => x < 0) === false);
assert([1, 2, 3, 4].every(x => x >= 0) === true);
Similar to some()
, the execution of every()
is short-circuited. As soon as every()
finds an array element that doesn't match the predicate, it immediately returns false
and doesn't iterate over the remaining elements.
#Additional Parameters
The predicate function is passed three arguments by both some()
and every()
: the current array element to test, the index in the array, and the array itself. You can evaluate those parameters however you like to determine whether to return true
or false
:
function predicate(element, index, array) {
// ...
}
Just like the other Array
methods, some()
and every()
accept an optional thisArg
as the second parameter (after the predicate). It specifies the value to use as this
when executing the predicate function.
#Browser Support and Polyfills
Having been released in 2009, ECMAScript 5 has very good browser support these days. From IE 9 onwards, all browsers support some()
and every()
. However, if you need to support older browsers, both methods can easily be polyfilled by attaching custom implementations to the prototype of the Array
object:
Array.prototype.some()
: documentation and polyfillArray.prototype.every()
: documentation and polyfill