6

Possible Duplicate:
What is the !! operator in JavaScript?

Sorry if this one is obvious but I can't google it.

What is the "!!" operator in Javascript? e.g.

if (!!window.EventSource) {
  var source = new EventSource('stream.php');
} else {
  // Result to xhr polling :(
}

Did the author just use "!" twice i.e. a double negation? I'm confused because this is in the official doc.

mfluehr
  • 2,832
  • 2
  • 23
  • 31
hbt
  • 1,011
  • 3
  • 16
  • 28

3 Answers3

10

It will convert anything to true or false:

!!0    // => false
!!1    // => true 
!!'a'  // => true
!!''   // => false
!!null // => false

Technically, !! is not an operator, it is just two ! operators next to each other. But a double-negation is pointless unless you are using !! like an operator to convert to Boolean type.

bowsersenior
  • 12,524
  • 2
  • 46
  • 52
  • +1 Nice answer! A lot clearer than mine. – vonconrad Dec 25 '10 at 08:10
  • @vonconrad: But IMHO your answer is better because one should in the first place explain that there is no such thing as an `!!` operator and only then explain that it is the side-effect of doing negation twice that is wanted. – slebetman Dec 25 '10 at 08:16
  • @slebetman: Fair point. Still, browsersenior's examples are better than mine. ;) – vonconrad Dec 25 '10 at 08:20
6

In most languages, !! is double negation, as ! is negation. Consider this:

# We know that...
!false == true

# And therefore...
!!false == false
!!true == true

It's often used to check whether a value exists and is not false, as such:

!!'some string' == true
!!123 == true
!!myVar == true
vonconrad
  • 25,227
  • 7
  • 68
  • 69
1

!! is used to convert a non-zero/non-null value to boolean true and a zero/null value to false.

E.g. if a = 4, then !a = false and !!a = !(!a) = true.

Joy Dutta
  • 3,416
  • 1
  • 19
  • 19