5

Is there any advantage, except indicating an explicit conversion, to using a double not operator in JavaScript? It oft' seems that these days, people like to check for existence of new APIs using the double not, but I have never, ever read any advantage to it.

if(!!window.File)
    // The File API is supported.
else
    // Your browser sucks.

The one thing that I have read is that it is a concise, obscure way to type cast to boolean, however, when used in this context the object will be auto coerced to boolean anyways since we are checking to see if it is defined.

In short, why do people do two boolean operations on top of the engine's?

Joshua W
  • 1,061
  • 12
  • 28
  • As demonstrated by the link, it globally make a conversion to a boolean. Here it's mainly intended as making the code more readable, meaning that only the boolean value is needed. – Denys Séguret Jun 10 '12 at 20:15
  • I know exactly what the !! pseudo operator does, that is not what I asked. – Joshua W Jun 10 '12 at 20:16
  • 2
    There is no real use, it's a bad habit having for pretext readability. – Denys Séguret Jun 10 '12 at 20:17
  • You've got me there, so now the only question is that of why it is in such common use. – Joshua W Jun 10 '12 at 20:26
  • @watkinsj. I've never seen it in a real serious library (like jQuery...). – gdoron is supporting Monica Jun 10 '12 at 20:42
  • The question referenced by creemama explicitly states that it is used in jQuery... – Joshua W Jun 10 '12 at 20:45
  • 1
    @watkinsj it's useful for APIs that insist on an actual boolean `true` or `false` value (like some jQuery APIs), and not just a value to be cast later. Sometimes APIs with optional parameters use `typeof` to figure out what a particular set of parameters is supposed to mean, so if it's necessary to pass in a real boolean, `!!` is a quick (and perfectly safe) way to do it. It's idiomatic, and any experienced JavaScript developer should be familiar with the idiom. – Pointy Jun 10 '12 at 21:08

2 Answers2

7

I don't really see any reason to do it in context like you present. It will not affect the result in any way.

The only time I'd see this as a good idea is if you're building a function which is supposed to return a bool value, and you need to cast it from some other value, eg...

function isNotFalsy(val) { return !!val; }

The example may be a bit forced, but you get the idea. You would always want to make sure the return value is of the type the user would expect.

Jani Hartikainen
  • 40,227
  • 10
  • 60
  • 82
  • Accepted as best, would like to point out @Pointy some APIs may ===/typeof to require boolean values. – Joshua W Jun 10 '12 at 22:34
1

You don't need to use !! inside an if expression.
It's being used the convert the value to a boolean, and the if does it by default.

var x = ""; // a falsy value
!x // true
!!x // false

if (x) === if (!!x)
gdoron is supporting Monica
  • 136,782
  • 49
  • 273
  • 342