Does the cart hold an out-of-stock item? Is one of the form fields empty? These questions expect a yes or a no, not a list.
some answers exactly that shape of question, and ends its walk the moment it has enough to answer.
Definition
some is an Array method returning true as soon as one item passes the test, and false when none does. Its opposite, every, returns true only when all of them pass.
const cart = [
{ name: "keyboard", stock: 0 },
{ name: "mouse", stock: 4 },
];
console.log(cart.some((a) => a.stock === 0)); // true
console.log(cart.every((a) => a.stock > 0)); // falseThe function receives the three usual arguments, the item, its index and the whole array, the last two being rarely used. As with Array.filter(), its return does not have to be a boolean: its Truthy and falsy nature is enough to decide.
Stopping early
The walk ends on the first success, which matters on a costly test or a long array.
const seen = [];
[1, 2, 3, 4, 5].some((n) => {
seen.push(n);
return n > 2;
});
console.log(seen); // [ 1, 2, 3 ]Three items visited out of five. every follows the mirror rule: it stops on the first failure, since one is enough to sink the whole set.
The empty-array case
This is the behavior that surprises most, and it is perfectly logical once stated the right way round.
console.log([].some(() => true)); // false
console.log([].every(() => false)); // truesome looks for an example and finds none, so it answers no. every looks for a counter-example and finds none either, so it answers yes. A test along the lines of "every field is filled in" is therefore true on a form with no fields, which often deserves a length check beforehand.
Frequently asked questions
some or includes?
includes looks for one precise value and compares with Strict equality (===), which keeps it to numbers, strings and booleans. On objects it always fails, unless the very same reference is compared. The moment a criterion is involved, some is the one.
How do you write the opposite of every?
With some and the test flipped: "all positive" is false exactly when "at least one zero or negative" is true. That rewrite avoids a ! sitting in front of a whole call, which the eye skips half the time, and it states plainly what the test is really after.
Is some faster than Array.filter()?
For answering a yes-or-no question, yes, and often by a wide margin. filter walks the entire array and builds a result whose length alone will be read, whereas some stops at the first item that fits.