Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling `every` and `some` methods of an empty array returns weird results [duplicate]

Tags:

javascript

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?

like image 968
Dima Parzhitsky Avatar asked Oct 31 '25 13:10

Dima Parzhitsky


1 Answers

"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"));
like image 104
pfg Avatar answered Nov 02 '25 04:11

pfg