JS surprise: Array.every() always returns true for empty arrays
- Published at
- Updated at
- Reading time
Nicholas C. Zakas published a discovery that made my head spin. Do you know the array method
This is how MDN describes what it does:
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:
And it gets every weirder. Check the results for an empty array with
.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. 💯