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.
!!1 // true
!!0 // false
!!undefined // false
!!{} // true
!![] // true
The first negation converts any value to false
if it is truthy and to true
if is falsy. The second negation then operates on a normal Boolean value. Together they convert any truthy value to true
and any falsy value to false
.
However, many professionals consider the practice of using such syntax unacceptable and recommend simpler to read alternatives, even if they're longer to write:
x !== 0 // instead of !!x in case x is a number
x != null // instead of !!x in case x is an object, a string, or an undefined
Usage of !!x
is considered poor practice due to the following reasons:
x !== 0
says that x
is probably a number, whereas !!x
does not convey any such advantage to readers of the code.Boolean(x)
allows for similar functionality, and is a more explicit conversion of type.