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

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>[].every(i => i instanceof Node) // -> true
</code>
<code>[].every(i => i instanceof Node) // -> true </code>
[].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…

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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)
</code>
<code>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) </code>
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 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.

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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>every = true && fn(val1) && fn(val2) && ...
some = false || fn(val1) || fn(val2) || ...
</code>
<code>every = true && fn(val1) && fn(val2) && ... some = false || fn(val1) || fn(val2) || ... </code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>arr.every(val => condition(val)) === !arr.some(val => !condition(val))
</code>
<code>arr.every(val => condition(val)) === !arr.some(val => !condition(val)) </code>
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 the every 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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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</code>
<code>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</code>
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.

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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</code>
<code>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</code>
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:

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<code>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</code>
<code>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</code>
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

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật