DEV Community

aprouja1
aprouja1

Posted on

An overlooked Array.every() gotcha

For those not familiar, the Array.every() method tests a condition against all items in an array:

const fruits = ["Apple", "Banana", "Plum","Orange"]

//Is every fruit longer than 5 characters?
fruits.every(fruit => fruit.length > 5) //false

Items are not just limited to simple strings:

const people= [{name:"Alex", age:24}, {name:"Bob", age:37},
{name:"Carl", age:18}, {name:"Devon", age:77}]

//Is every person at least 18 years old
people.every(person => person.age >= 18) //true

//destructured
people.every(({age}) => age >= 18) //true


But did you know what happens with an empty array:

const toDoListItems = []

//Are all of my items complete
toDoListItems.every(item => item.done === true) //true

Well that was unexpected. Turns out that when every is called on an empty array, the result is always true: MDN - Array.every()

Be careful not to use the Array.every() method when your Array may have a length of 0.

Top comments (2)

Collapse
 
titasgailius profile image
Titas Gailius

Why? That is very intuitive and expected.

Collapse
 
aprouja1 profile image
aprouja1

Well i guess that is just for me then. Hopefully no one else will need this information, but if they do I will direct them your way :)