7

I came across the !! (not not) operator in javascript as a way of converting a falsy/truthy value to inverted true/valse and then invert it to get the corresponding true/false. So apparently

!!("something")

and

Boolean("something")

are the same. Are there any differences between them? Which one is the preferred one?

I found some related questions ( What is the !! (not not) operator in JavaScript?) but they don't seem to address performance. I hope this is not a duplicate.

Community
  • 1
  • 1
Entomo
  • 275
  • 3
  • 12
  • 3
    Is your application really so strained on performance that this matters? – Matti Virkkunen Oct 01 '14 at 12:24
  • Not an answer to your question: do you have any real world situation where you may even care of any (even measurable) performance gain about this? – Adriano Repetti Oct 01 '14 at 12:24
  • 2
    For what it's worth, there is a jsPerf benchmark available [here](http://jsperf.com/bang-bang-vs-boolean). – Frédéric Hamidi Oct 01 '14 at 12:25
  • 1
    http://jsperf.com/boolean2 – CD.. Oct 01 '14 at 12:25
  • 1
    Not much difference..Check this out: http://jsperf.com/bool-not-not – Sachin Jain Oct 01 '14 at 12:25
  • @AdrianoRepetti yes. My curiousness. – Entomo Oct 01 '14 at 12:26
  • @Entomo good reason! Well I think _code path_ for such things is pretty variable and you'll get completely different results on, for example, Chrome and IE. Not so reliable tests... – Adriano Repetti Oct 01 '14 at 12:28
  • OK. the links provided are interesting so I will have a look. Thanks – Entomo Oct 01 '14 at 12:29
  • 1
    @blunderboy the test was wrong, as the `||` meant it only did the first conversion and skipped the rest. I've fixed it now. – OrangeDog Oct 01 '14 at 13:04
  • `!!x` and `new Boolean(x)` are not the same: if you compare those two expressions, they will fail a strict equality check (`===`) and they give different results for `typeof` (which is why they fail the strict equality). `new Boolean` creates an object, while `!!` returns a primitive. – apsillers Oct 01 '14 at 14:36
  • 1
    !!x and Boolean(x) pass the equality check. new Boolean(x) is false indeed. – Entomo Oct 01 '14 at 14:40
  • 3
    @Quentin, I don't see this answered in the duplicated post in any way. Not at the first peek at least and I don't want to spend my morning digesting that other huge one. Please, revert the duplicated post. I already know how to fish but in this case I want a steamy delicious baked fish instead of a fishing cane, if you know what I mean. – Adminiculo Aug 26 '19 at 15:19
  • #ANSWER: They're pretty close as far as performance goes. I ran the tests and some times they came out one faster than the other, but sometimes it went the other way. **It's a toss up**. The bigger question is **readability**. Boolean is definitely more explicit and easy for anyone to understand. !! has a much smaller footprint. *It's up to your team which to use.* – Michael Cox Nov 15 '19 at 20:33

0 Answers0