JavaScript !! (not not | double negative) Operator Explanation

JavaScript has a confusing set of rules for what is considered “true” and “false” when placed in a context where a Boolean is expected. But the logical-NOT operator, !, always produces a proper Boolean value (one of the constants true and false). By chaining two of them, the idiom !!expression produces a proper Boolean with the same truthiness as the original expression.

Why would you bother? Because it makes functions like the one you show more predictable. If it didn’t have the double negative in there, it might return undefined, a Function object, or something not entirely unlike a Function object. If the caller of this function does something weird with the return value, the overall code might misbehave (“weird” here means “anything but an operation that enforces Boolean context”). The not not or double-negative idiom prevents this.

  1. A logical NOT operator ! converts a value to a boolean that is the opposite of its logical value.
  2. The second ! converts the previous boolean result back to the boolean representation of its original logical value.

!! coerces object to be boolean. To elaborate, it converts a non-boolean to a boolean, then inverts it to be original logical value.

So if Object gives you a “falsey” value, the !! will make it return the boolean value false. Otherwise it will return true.

The “falsey” values are:

  • false
  • NaN
  • undefined
  • null
  • "" (empty string)
  • 0

For clarity you would be better off using Boolean(Object). Boolean() creates a boxed boolean, which does not behave the same as the primitive booleans created by !! (for instance, typeof will report “object”). Thus, !! is preferred.

To make it return primitive boolean:

To use in condition:

More Examples:


One thought on “JavaScript !! (not not | double negative) Operator Explanation

Leave a Reply

Your email address will not be published. Required fields are marked *