JavaScript: Can I use a Boolean object as a callback function?

I would like to write array.some(Boolean) as a way to check if any elements from array plausible.

Are there any problems using the Boolean object this way? Does it have the same behavior in modern browsers? Is this always equivalent to array.some(function(elem) { return !!elem; }) ?

+7
javascript callback ecmascript-6 boolean
source share
1 answer

Are there any problems using the Boolean object this way?

Not. Unlike parseInt for example (which would be problematic), Boolean expects only one argument. Therefore, there should be no problem passing other callback arguments (index and array) to it; they simply ignore them.

Does it have the same behavior in modern browsers?

I hope so. If you cannot trust the Boolean function, what else is left?

Is this always equivalent to array.some(function(elem) { return !!elem; }) ?

Yes. From spec :

When a Boolean is called as a function, not as a constructor, it performs type conversion.

And that essentially what it does !! .


Relevant links from the specification:

+7
source share

All Articles