Use some() and every() on arrays in JavaScript
Beginner · 4 min read
Lots of everyday checks are yes-or-no questions about a whole list. Is any item out of stock? Are all the form fields filled in? Has any player reached 100 points? Did every test pass? JavaScript answers these with two methods: some for "is any of them...?" and every for "are all of them...?".
In this tutorial you will use both on a list of temperatures, count how early each one stops, and then run them on an empty array, where the answers surprise most people. You should know arrays and arrow functions.
Predicates, again
Both methods take a predicate: a function that receives one item and returns true or false.
const isHot = (t) => t > 23;
console.log(isHot(24)); // true
console.log(isHot(19)); // false
some(isHot) asks "does isHot say yes for at least one item?". every(isHot) asks "does it say yes for every item?". Both return a plain true or false.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
12 some and every
easyAnswer "is any of them over 23?" and "are all of them over 18?". Then run both against an empty array and explain the results.
Stuck? Three hints, smallest first
- 1.
somestops at the firsttrue;everystops at the firstfalse. - 2. On an empty array they do not agree. One is
true, the otherfalse. - 3. "All of nothing satisfies the rule" is vacuously true — there is no counter-example to find.
Step 1: is any of them over 23?
const temps = [21, 24, 19];
console.log(temps.some((t) => t > 23)); // true
24 is over 23, so the answer is yes. One match is enough.
Step 2: are all of them over 18?
const temps = [21, 24, 19];
console.log(temps.every((t) => t > 18)); // true
console.log(temps.every((t) => t > 22)); // false
21, 24 and 19 are all above 18, so every says yes. Above 22 fails: 21 doesn't make it, and one failure is enough for every to say no.
Step 3: they stop early
Add a counter to see how many items each method looks at.
const temps = [21, 24, 19];
let someCalls = 0;
const anyHot = temps.some((t) => { someCalls++; return t > 23; });
let everyCalls = 0;
const allWarm = temps.every((t) => { everyCalls++; return t > 22; });
console.log(anyHot, someCalls); // true 2
console.log(allWarm, everyCalls); // false 1
some checked 21 (no), then 24 (yes), and stopped: it already had its answer. every checked 21, which failed, and stopped straight away. some stops at the first true, every stops at the first false. This is called short-circuiting.
It is good news when the check is slow. It also means your predicate may not run for every item, so don't put work inside it that must happen for each one.
Step 4: the empty array
Now try both on an array with nothing in it. Give some a predicate that always says yes, and every one that always says no.
console.log([].some(() => true)); // false
console.log([].every(() => false)); // true
The first is easy: there is no item, so no item matches, so some is false.
The second looks wrong. How can every be true with a predicate that is never true? Think of every as asking "is there an item that fails?". It looks for a counter-example. An empty array has no items, so there is nothing that fails, so the answer is yes. Mathematicians call this vacuous truth: "all of nothing" passes any rule.
Step 5: where vacuous truth bites
This matters in real code. Picture a form check:
const isFilled = (field) => field.value !== '';
const fields = [];
console.log(fields.every(isFilled)); // true
console.log(fields.length > 0 && fields.every(isFilled)); // false
If the list of fields is empty, perhaps because it failed to load, every says the form is valid. When "nothing at all" should not count as passing, check length first. && only runs the right side when the left side is true.
Step 6: some works on objects too
includes can't find objects, because two separate objects are never equal. some with a predicate can.
const rows = [{ id: 1 }, { id: 2 }];
console.log(rows.includes({ id: 1 })); // false
console.log(rows.some((r) => r.id === 1)); // true
And the two methods are linked: "none of them is over 30" is the same question as "all of them are 30 or under".
const temps = [21, 24, 19];
console.log(!temps.some((t) => t > 30)); // true
console.log(temps.every((t) => t <= 30)); // true
The full solution
The panel asks both questions about the temperatures, prints how many calls each needed, and runs both methods on an empty array. Press Run to see the output.
const temps = [21, 24, 19];
let someCalls = 0;
const anyHot = temps.some((t) => { someCalls++; return t > 23; });
let everyCalls = 0;
const allWarm = temps.every((t) => { everyCalls++; return t > 22; });
console.log('some(t > 23) :', anyHot, ' after', someCalls, 'of 3 calls');
console.log('every(t > 22):', allWarm, ' after', everyCalls, 'of 3 calls');
console.log('every(t > 18):', temps.every((t) => t > 18));
console.log('--- the empty array ---');
console.log('[].some(...) :', [].some(() => true));
console.log('[].every(...) :', [].every(() => false), '<- true, with a predicate that is never true');
console.log('every is "no counter-example exists", and an empty list has none');
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('some finds a match', anyHot, true);
test('some stopped at the second element', someCalls, 2);
test('every fails on the first element that does not qualify', allWarm, false);
test('and it stopped there', everyCalls, 1);
test('every is true when they all qualify', temps.every((t) => t > 18), true);
test('some on an empty array is false', [].some(() => true), false);
test('every on an empty array is true, whatever the predicate', [].every(() => false), true);
test('some is also the readable way to ask about objects', [{ id: 1 }].some((r) => r.id === 1), true);
test('but on a real array, not-some is every-with-the-test-flipped', !temps.some((t) => t > 30) === temps.every((t) => t <= 30), true);
[].every(() => false) being true looks wrong and is not. every asks whether any element fails; an empty array has no elements, so nothing fails, so the answer is true. Mathematicians call it vacuous truth, and it bites when validating: fields.every(isValid) passes an empty form. Check for emptiness separately.
Both short-circuit, which makes them the right tools for an expensive predicate — and the wrong tools if the predicate has side effects you were relying on, since it may not run for every element.
Common mistakes
- Trusting
everyon a list that might be empty. It returnstrue. Addxs.length > 0 &&when empty should fail. - Expecting the predicate to run for every item. Both methods stop as soon as they know the answer. Use
forEachfor side effects. - Using
filter(...).length > 0for "is there any?". It works, but it visits every item and builds an array you throw away.somesays it directly.
Try it yourself
- Check whether any word in
['sun', 'moon', 'starlight']is longer than 8 letters. - Check whether every number in
[2, 4, 7]is even, and count how many calls the predicate needed. - Write
none(xs, pred)usingsome, and decide what it should return for an empty array.