18

I'm looking over a book for html 5 and it includes this tid bit of js. What does double exclamation mean?

return ! ! document.createElement('video').canPlayType;
steve
  • 181
  • 1
  • 3
  • 4
    Got to love it, double negatives useful in programing languages. And my english teacher said never use double negative. "I do not want to do nothing." becomes a sentence that perhaps makes sense now. :) – John Hartsock Dec 22 '10 at 19:07
  • 1
    I may be an ideaa to first try searching stackoverflow before asking. http://stackoverflow.com/questions/784929/what-is-the-operator-in-javascript – KooiInc Dec 22 '10 at 19:07
  • 1
    sorry about that. i did a search under "double exclamation points javascript" Didn't pull up anything. – steve Dec 22 '10 at 19:09

2 Answers2

23

The ! operator negates, and the secondary ! negates the result of the inital negation. This basically typecasts whatever is on the right hand side into a boolean ( true or false ).

!false // true
!!false // false

So if the method is defined then the function which is truthy, will be typecasted into true.

document.createElement('video').canPlayType

So the above returns a function. We don't want a function, we want an explicit boolean, so we negative it twice and since function is not falsy ( 0, null, false, empty string, NaN ) then it returns true for browsers which support this method.

!!document.createElement('video').canPlayType // true

If the method is not supported, the browser will return undefined. !undefined is true, and !true is false, so !!document.createElement('video').LOL will return false

meder omuraliev
  • 183,342
  • 71
  • 393
  • 434
  • wouldn't `document.createElement('video').canPlayType` return a boolean? Or is it for if that is `null` then `!!(null) = false`? – hunter Dec 22 '10 at 19:05
  • @hunter - document.createElement('video').canPlayType will return undefined if the browser doesn't support the video tag. – James Kovacs Dec 22 '10 at 19:07
  • ... javascript is dumb ... `!null` should throw an exception... dangit – hunter Dec 22 '10 at 19:21
9

The double exclamation is a JavaScript trick to return true/false regardless of input. In your example, if a browser does not support the video tag, it will return undefined. !undefined is true. So !!undefined is false. If the browser does support video, it will return true. !!true is also true. This saves you from having to handle the case of undefined.

James Kovacs
  • 11,549
  • 40
  • 44