JavaScript Double Negation (!!x)


Example

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:

  1. Stylistically it may look like a distinct special syntax whereas in fact it is not doing anything other than two consecutive negations with implicit type conversion.
  2. It is better to provide information about types of values stored in variables and properties through the code. For example, x !== 0 says that x is probably a number, whereas !!x does not convey any such advantage to readers of the code.
  3. Usage of Boolean(x) allows for similar functionality, and is a more explicit conversion of type.