Why does Array.prototype.every return true on an empty array? Why does Array.prototype.every return true on an empty array? arrays arrays

Why does Array.prototype.every return true on an empty array?


See the docs

every acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true. (It is vacuously true that all elements of the empty set satisfy any given condition.)

As an edit, because I looked Vacuous truth up. I understood it from context, but I was interested in the formal definition. This paraphrased quote exemplifies the meaning:

"You are my favorite nephew" is a vacuous statement if he is the only nephew: there are no others to consider.


From the ECMAScript specification of Array.prototype.every (bold emphasis mine):

every calls callbackfn once for each element present in the array, in ascending order, until it finds one where callbackfn returns false. If such an element is found, every immediately returns false. Otherwise, if callbackfn returned true for all elements, every will return true.

[...] every acts like the "for all" quantifier in mathematics. In particular, for an empty array, it returns true.

Considering the first bolder phrase above: since every finds no elements for which the callback return false (because the callback never even runs, because there are no elements), it returns true, as confirmed by the second bolded phrase.


It's more mathematically valid to say "every" is - vacuously - true if there are no elements.

You need it so the relationship "for all x, P" is the same as "NOT(there exists x such that not P)".

It's somewhat a matter of convention but it does "make the math work out nicely" quite often.