Using JavaScript, is there any difference between
Boolean(x)
and
!!x
?
They both have the same output, but you have to watch out for the Boolean object vs function. The Boolean constructor (using the new keyword) is not a primitive true
or false
value. Whereas the !! operator evaluates if an object is truthy/falsey.
Here's a quote from MDN:
Any object of which the value is not undefined or null, including a Boolean object whose value is false, evaluates to true when passed to a conditional statement.
So the following evaluates to false:
new Boolean(false) === false
but the following evaluates to true:
Boolean(false) === false
What's also an interesting difference between them is that you are able to explicitly pass Boolean
as an callback inside Array#filter
function, while if you would like to use !!
, you'd would firstly have to set a callback function and then return it.
.filter(Boolean)
✓
.filter(!!)
✕
.filter((x) => !!x)
✓ (can be simplified, though - .filter((x) => x)
)