Brew some tea:
!!
is not an operator. It is the double-use of !
-- which is the logical "not" operator.
In theory:
!
determines the "truth" of what a value is not:
!!
determines the "truth" of what a value is not not:
What we wish to determine in the comparison is the "truth" about the value of a reference, not the value of the reference itself. There is a use-case where we might want to know the truth about a value, even if we expect the value to be false
(or falsey), or if we expect the value not to be typeof boolean
.
In practice:
Consider a concise function which detects feature functionality (and in this case, platform compatibility) by way of dynamic typing (aka "duck typing"). We want to write a function that returns true
if a user's browser supports the HTML5 <audio>
element, but we don't want the function to throw an error if <audio>
is undefined; and we don't want to use try ... catch
to handle any possible errors (because they're gross); and also we don't want to use a check inside the function that won't consistently reveal the truth about the feature (for example, document.createElement('audio')
will still create an element called <audio>
even if HTML5 <audio>
is not supported).
Here are the three approaches:
// this won't tell us anything about HTML5 `<audio>` as a feature var foo = function(tag, atr) { return document.createElement(tag)[atr]; } // this won't return true if the feature is detected (although it works just fine) var bar = function(tag, atr) { return !document.createElement(tag)[atr]; } // this is the concise, feature-detecting solution we want var baz = function(tag, atr) { return !!document.createElement(tag)[atr]; } foo('audio', 'preload'); // returns "auto" bar('audio', 'preload'); // returns false baz('audio', 'preload'); // returns true
Each function accepts an argument for a <tag>
and an attribute
to look for, but they each return different values based on what the comparisons determine.
But wait, there's more!
Some of you probably noticed that in this specific example, one could simply check for a property using the slightly more performant means of checking if the object in question has a property. There are two ways to do this:
// the native `hasOwnProperty` method var qux = function(tag, atr) { return document.createElement(tag).hasOwnProperty(atr); } // the `in` operator var quux = function(tag, atr) { return atr in document.createElement(tag); } qux('audio', 'preload'); // returns true quux('audio', 'preload'); // returns true
We digress...
However rare these situations may be, there may exist a few scenarios where the most concise, most performant, and thus most preferred means of getting true
from a non-boolean, possibly undefined value is indeed by using !!
. Hopefully this ridiculously clears it up.