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

[].every(i => i instanceof Node) // -> true 

Why does each array method in JavaScript return true when the array is empty. I'm trying to make a type statement like this ...

 let isT = (val, str) => typeof val === str, is = {}, nT = (val, str) => !isT(val, str); is.Undef = (...args) => args.every(o => isT(o, 'undefined')); is.Def = (...args) => args.every(o => nT(o, 'undefined')); is.Null = (...args) => args.every(o => o === null); is.Node = (...args) => args.every(o => o instanceof Node); is.NodeList = (...args) => Array.from(args).every(n => is.Node(n)); 

but they still return to the truth, even when no arguments are passed to them.

+6
source share
4 answers

See documents

each acts as a "for all" quantum in mathematics. In particular, for an empty array, it returns true. (This is empty! That all elements of an empty set satisfy any given condition.)

Like editing because I watched Free Truth . I understood this from the context, but I was interested in a formal definition. This paraphrase quotation illustrates the meaning:

“You are my beloved nephew” is an empty phrase if he is the only nephew: there is no need to consider others.

+5
source

This is more mathematically true to say that "each" is - vacuously - true if there are no elements.

You need the relation “for all x, P” to be the same as “NOT (there is x such that not P)”.

This is somewhat arbitrary, but it "makes math work well" quite often.

+3
source

MDN Array each ()

each acts as a "for all" quantum in mathematics. In particular, for an empty array, it returns true. (It is clear that all elements of the empty set satisfy any given condition.)

+2
source

From the ECMAScript specification Array.prototype.every (my bold accent):

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

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

Given the first bolder phrase above: since every does not find elements for which the callback returns false (since the callback never starts because there are no elements), it returns true , which confirms the second bold phrase.

+2
source

All Articles