1

Using JavaScript, is there any difference between

Boolean(x)

and

!!x

?

  • 1
    They produce the same result of converting your value `x` into a boolean. However, one is certainly shorter and for that reason you'll see it used frequently when minifying your javascript. – CRice Nov 13 '17 at 21:23
  • 3
    **explicit** vs **implicit**. – ibrahim mahrir Nov 13 '17 at 21:24
  • Possible duplicate of [What is the !! (not not) operator in JavaScript?](https://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript) – Mykola Borysyuk Nov 13 '17 at 21:26
  • 1
    Also from duplicated answer.. Here you go `Boolean(foo) === !!foo` but `new Boolean(foo) !== !!foo` .. JS :D – Mykola Borysyuk Nov 13 '17 at 21:30

2 Answers2

2

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

Micaiah Wallace
  • 1,101
  • 10
  • 17
  • 3
    `Boolean(false)` is not the Boolean constructor, it's the Boolean function. You're thinking of `new Boolean(false)` – Hamms Nov 13 '17 at 21:26
1

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))

kind user
  • 40,029
  • 7
  • 67
  • 77