[].every(i => i instanceof Node) // -> true
Why does the every method on arrays in JavaScript return true when the array is empty. I’m trying to do type assertion like so…
const isT = (val, str) => typeof val === str
const nT = (val, str) => !isT(val, str)
const is = {}
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) => args.every(n => n instanceof NodeList)
but these still return true even when no arguments are passed to them.
1
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.
8
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 returnsfalse
. If such an element is found, every immediately returnsfalse
. Otherwise, if callbackfn returnedtrue
for all elements,every
will returntrue
.[…]
every
acts like the “for all” quantifier in mathematics. In particular, for an empty array, it returnstrue
.
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.
1
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.
MDN Array every()
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.)
I read this somewhere, but can’t find the source anymore. The blog post is short, titled “Intuition to .some()
and .every()
” or something like that.
every = true && fn(val1) && fn(val2) && ...
some = false || fn(val1) || fn(val2) || ...
This is one of the greatest mini blog post I’ve ever seen. Hope someone can find it.
One compelling reason I see is that the following is always expected to be true:
arr.every(val => condition(val)) === !arr.some(val => !condition(val))
When arr
is empty, then there is no problem to see that the expression at the right should be true, i.e. some()
returns false for an empty array, as obviously there isn’t any member that satisfies the (opposite) condition.
We can also refer to the field of logic, as every
really represents a conjuction, for which Wikipedia notes:
In keeping with the concept of vacuous truth, when conjunction is defined as an operator or function of arbitrary arity, the empty conjunction (AND-ing over an empty set of operands) is often defined as having the result true.
A question on math.stackexchange was Is an empty conjunction in propositional logic true?, where the accepted answer points to true
being the identity of the conjuction relation.
Wikipedia, has a mention of JavaScript’s every
function in its article of vacuous truth:
Many programming environments have a mechanism for querying if every item in a collection of items satisfies some predicate. It is common for such a query to always evaluate as true for an empty collection. For example:
- In JavaScript, the array method
every
executes a provided callback function once for each element present in the array, only stopping (if and when) it finds an element where the callback function returns false. Notably, calling theevery
method on an empty array will return true for any condition.- […]
We can also compare this with the arithmetic product of an empty array. JavaScript has no such function, but the question has been asked for Python: Why product of empty list output is “1”?
It is essentially defaulting to true
outside of the loop.
function every(arr, callback) {
for (let item of arr) {
if (!callback()) {
return false; // Short-circuit
}
}
return true; // Default return
}
let x = [], isNode = e => e instanceof Node, isValid = every(x, isNode);
console.log(isValid); // true
Whereas with some
, it defaults to false
.
function some(arr, callback) {
for (let item of arr) {
if (callback()) {
return true; // Short-circuit
}
}
return false; // Default return
}
let x = [], isNode = e => e instanceof Node, isValid = some(x, isNode);
console.log(isValid); // false
Alternatively, you can write a convenience wrapper:
const everyStrict = (arr, callback) =>
arr != null && arr.length > 0 && arr.every(callback);
let x = [], isNode = e => e instanceof Node, isValid = everyStrict(x, isNode);
console.log(isValid); // false