Why does [].every(el => el.selected) return true ?

Reported as a duplicate at Grundy. javascript September 16 '18 at 11:12 .

A similar question was asked earlier and an answer has already been received. If the answers provided are not exhaustive, please ask a new question .

  • Language is not so important, so duplicate , IMHO. @Athari gave a very good and clear answer on this topic - Kir_Antipov

2 answers 2

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

Note: This method returns true for any condition.

Note: This method returns true for any condition applied to an empty array.

    In general, as a rule, this function is determined by convention. In Haskel, for example,

     all :: (a -> Bool) -> [a] -> Bool all p = and . map p and :: [Bool] -> Bool and = foldr (&&) True 

    (True in the last line is just the initial value, which is returned for an empty array.)

    Actually, this allows you to define a function recurrently. In pseudocode, there would be something like:

     every(arr, pred) = now_and_then(arr, pred, 0) where now_and_then(arr, pred, i) = i == arr.length || pred(arr[i]) and now_and_then(arr, pred, i + 1) 

    When going beyond the array, in this case it is better to return True, otherwise the case of an empty array would have to be analyzed separately.

    Well and, actually, the logical definition: "For any element of the array, the predicate is true." In an empty array, obviously, this is true: the negation of the statement - "There is an element in the array, such that the value of the predicate for this element is false," - but there is no such element in the empty array.