The double-negation !! is not a distinct JavaScript operator nor a special syntax but rather just a sequence of two negations. It is used to convert the value of any type to its appropriate true or false Boolean value depending on whether it is truthy or falsy.
It first negates the result of the expression, then it negates it again. In this way if you had a non-zero number, a string, an object, an array, or anything that's truthy, you'll get true back. Otherwise you'll get false .
(unless you're writing in JavaScript, in which case it's perfectly ok). 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.
If you place this operator in front of a boolean value, it will reverse the value, returning the opposite. If the single bang returns the opposite boolean value, imagine what double-bang would return? The associated boolean value. In other words, true or false according to whether it is truthy or falsy values.
It casts to boolean. The first !
negates it once, converting values like so:
undefined
to true
null
to true
+0
to true
-0
to true
''
to true
NaN
to true
false
to true
false
Then the other !
negates it again. A concise cast to boolean, exactly equivalent to ToBoolean simply because !
is defined as its negation. It’s unnecessary here, though, because it’s only used as the condition of the conditional operator, which will determine truthiness in the same way.
var x = "somevalue"
var isNotEmpty = !!x.length;
Let's break it to pieces:
x.length // 9
!x.length // false
!!x.length // true
So it's used convert a "truethy" \"falsy" value to a boolean.
The following values are equivalent to false in conditional statements:
""
(\ ''
)All other values are equivalent to true.
Double-negation turns a "truthy" or "falsy" value into a boolean value, true
or false
.
Most are familiar with using truthiness as a test:
if (options.guess) {
// runs if options.guess is truthy,
}
But that does not necessarily mean:
options.guess===true // could be, could be not
If you need to force a "truthy" value to a true boolean value, !!
is a convenient way to do that:
!!options.guess===true // always true if options.guess is truthy
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