0

Possible Duplicate:
What is the !! (not not) operator in JavaScript?
Can someone explain this ‘double negative’ trick?

Because I'm playing around with the HTML5 video possibilities, I came across getUserMedia.js, which offers cross browser support.

While investigating how the library works (and trying to get it working in a requirejs module), I found the following strange if construct:

if ( !! navigator.getUserMedia_) {
   ...

Double negation? What does it mean and why? Why not simple use the following?

if (navigator.getUserMedia_) {
   ...
Community
  • 1
  • 1
asgoth
  • 35,552
  • 12
  • 89
  • 98

3 Answers3

3

Double negation !! in JavaScript simply converts values to boolean type.

VisioN
  • 143,310
  • 32
  • 282
  • 281
  • But why is it 'better' than the second construct. Since navigator.getUserMedia_ is (or should be) a function, why not use `typeof navigator.getUserMedia_ === 'function'`. My question was not only what it means, but in what cases it should be used. – asgoth Jan 15 '13 at 17:36
  • @asgoth I can't say that this is "better". For me it is redundant. `!!` simply gives you the explicit `true` or `false` value, whereas condition in `if` clause checks if the value is not falsey (i.e. not `""`, `0`, `NaN`, `null`, `undefined`, or `false`). So in your example we can easily omit the type conversion. – VisioN Jan 15 '13 at 17:45
2

!! is usually used for casting variables to boolean (enforcing the boolean context)

That's used because different types can be evaluated to false, for example undefined, null, '', etc.

If you use: !!undefined, you get:

  1. !!undefined
  2. !true
  3. false

In that way you actually get the boolean value which is equals to the argument if is being evaluated in boolean context.

Minko Gechev
  • 25,304
  • 9
  • 61
  • 68
0

It's not an operator exactly, it's two of the same (!) which basically converts anything into a boolean. In other words, take the double negative of a value.

Jordan Kasper
  • 13,153
  • 3
  • 36
  • 55