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;
The double exclamation point, or double bang, converts a truthy or falsy value to “true” or “false”. In other words, it operates exactly like Boolean(value) would.
This punctation emoji of a double exclamation mark features two big red exclamation points that can be used to express surprise, shock, or to really emphasize or drive home a point.
In JavaScript, the double exclamation operator converts an Object to Boolean. This happens such that “falsy” objects become false and “truthy” objects become true.
Use the number of exclamation points that's in your heart. Language is supposed to help you communicate what you mean, so if you need two exclamation points for an extra-emphatic opinion and 27 for an announcement to your brother about your promotion, go for it.
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With