Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Can the Boolean object be used as a callback function?

I would like to write array.some(Boolean) as a way to test if any elements in array are truthy.

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

like image 435
Maros Avatar asked May 25 '16 20:05

Maros


1 Answers

Are there any issues with using the Boolean object in this way?

No. Unlike parseInt for example (which would be problematic), Boolean only expects a single argument. So there shouldn't be any issues with passing the other callback arguments to it (index and the array), it will simply ignore them.

Does it have the same behavior across modern browsers?

I do hope so. If you can't trust the Boolean function, what else is left?

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

Yes. From the spec:

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

And that's essentially what !! does as well.


Relevant references from the spec:

  • Boolean function
  • ! operator
  • (internal) ToBoolean function
like image 175
Felix Kling Avatar answered Nov 02 '22 06:11

Felix Kling