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.

2

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

3 Comments

+1 Nice answer! A lot clearer than mine.
@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: Fair point. Still, browsersenior's examples are better than mine. ;)
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

Comments

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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.