JS surprise: Array.every() always returns true for empty arrays
- Published at
- Updated at
- Reading time
- 2min
JavaScript is always good for a surprise, isn't it?
Nicholas C. Zakas published a discovery that made my head spin. Do you know the array method every
?
This is how MDN describes what it does:
The every()
method of Array instances tests whether all elements in the array pass the test implemented by the provided function. It returns a Boolean value.
Cool, that makes sense.
const collection = ['great', 'nope', 'great'];
const allItemsAreGreat = collection.every((item) => item === 'great'); // false
But now, see what happens when you use every
with an empty array.
[].every((item) => item === 'great'); // true
[].every((item) => item !== 'great'); // true
Whoops?! I didn't expect that every()
will tell me that every item matches my condition if there are none. That's not how my brain works.
When using the array method, you have to flip around your mindset. Here's Nicholas:
I’d suggest changing the way you read every() calls when you come across them. Instead of reading every() as “does every item in this array match this condition?” read it as, “is there any item in this array that doesn’t match this condition?”.
And it gets every weirder. Check the results for an empty array with some()
.
[].some((item) => item === 'great'); // false
[].some((item) => item !== 'great'); // false
Oh boy... Why do the array methods behave that way? The answer is Math, and if you want to dive deeper, check Nicholas' post. 💯
Join 5.5k readers and learn something new every week with Web Weekly.