In JavaScript why does the line [].every(Boolean) return true? And [].some(Boolean) returns false?
If there are no elements in the array, then they are kind of undefined (undeclared), thus falsy. According to this, snippets with arrays [null] or [undefined], return false exactly as predicted.
But any empty array should not call the callback Boolean at the first place, and return something like undefined or null, thus false again.
What I've missed?
It looks like, what JS interpreter really does is that Boolean([]) (in the first situation). And that of course returns true. Maybe that is correct?
"every" returns true if every element of an array passes a test. If there are no items in the array, "every" element in the array passes the test.
"some" returns true if at least one element of an array passes a test. If the array is empty, none of the elements pass the test and it returns false.
It looks like, what JS interpreter really does is that Boolean([]) (in the first situation). And that of course returns true. Maybe that is correct?
With an empty array, neither every nor some call the callback at all because there is nothing to test. You can check this with:
[].every(() => console.log("this never prints"));
[].some(() => console.log("this never prints"));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With