Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the "!!" operator in Javascript? [duplicate]

Tags:

javascript

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.

like image 683
hbt Avatar asked Dec 25 '10 07:12

hbt


2 Answers

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.

like image 70
bowsersenior Avatar answered Sep 28 '22 12:09

bowsersenior


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
like image 28
vonconrad Avatar answered Sep 28 '22 12:09

vonconrad