JavaScript
Article

JavaScript Double Negation (!!) Trick or Trouble?

By Sam Deering

So I was being asked to include some double negation comparison operators in my JavaScript Shorthands Techniques post and decided to have a closer look at whether or not we could be using it more often in our code. See speed tests below.

!! is not an operator. It’s just the ! operator twice

Examples:

success = !!what()&&that()
return !!value

var x = "somevalue"var isNotEmpty = !!x.length;
Let's break it to pieces:
x.length   // 9
!x.length  // false
!!x.length // true

The following values are equivalent to false in conditional statements:

* false
	* null
	* undefined
	* The empty string "" ( '')
	* The number 0
	* The number NaN

All other values are equivalent to true.

!!false === false
           !!true === true

              !!0 === false!!parseInt("foo") === false // NaN is falsy
              !!1 === true
             !!-1 === true  // -1 is truthy

             !!"" === false // empty string is falsy
          !!"foo" === true  // non-empty string is truthy
        !!"false" === true  // ...even if it contains a falsy value

     !!window.foo === false // undefined is falsy
           !!null === false // null is falsy

             !!{} === true  // an (empty) object is truthy
             !![] === true  // an (empty) array is truthy; PHP programmers beware!

You can also use the constructor functions corresponding to the primitive types (without using new) to explicitly cast values, ie

Boolean(foo) === !!foo
Number(foo)  === +foo
String(foo)  === ''+foo

And more examples!

return !!window; //Returns true
return !!null; //Returns false
return !!undefined; //Returns false
return !!false; //Returns false
return !!true; //Returns true
return !!""; //Returns false
return !!"Hi"; //Returns true
return !!0; //Returns false
return !!1; //Returns true

The first negation converts the data (whatever it data type it may be) to a boolean. The second negation changes the boolean again to give the desired result. Negative caseIf the value is null/undefined/false/””/0, then the first negation converts it to true. The second negation changes it to false.

Positive Case

If the value is object/true/”Value”/1, then the first negation converts it to false. The second negation changes it to true.

Is double negation !!(expr) the same as Typecasting Boolean(expr)

Yes.

Boolean(5) === !!5; Same casting, fewer characters.

But saying that look at this one! Brain hurty?

!!new Boolean(false) // true
!!Boolean(false) // false

Voila, explanations:

new Boolean(false) is an object and an object is truthy even if it contains a falsy value!
Boolean(false)returns the primitive false.

Speed tests!

double-negation-is-fastest

boolean-vs-double-negation

testrz

Reasons for using Double Negation

Some people call it the “Javascript double negative trick”. Essentially it converts a value (null, undefined, objects etc…) to a primitive Boolean value. Similar to typecasting explicitly using Boolean(value) except this converts the value to a Bololean Object and is not a true boolean. The double negation trick could be used to ensure that a return value is always boolean type in methods that returns a boolean value based on some condition.

Reasons against using Double Negation

Harder to read and understand. It’s a horribly obscure way to do a type conversion. ! is NOT. So !true is false, and !false is true. !0 is true, and !1 is false.

// Maximum Obscurity:
val.enabled = !!userId;

// Partial Obscurity:
val.enabled = (userId != 0) ? true : false;

// And finally, much easier to understand:
val.enabled = (userId != 0);

Double Negation in the real world

Google Closure compiler
Worth noting that some minifiers (such as Google’s Closure Compiler) turn true into !0 and falseinto !1 to save characters (note that the order looks awkward but is correct, !0 === true && !1 === false).

Detecting HTML5 Feature Support
We want to write a function that returns true if a user’s browser supports the HTML5

// this won't tell us anything about HTML5 `

Further reading:
Javascript double negative trick
Double bitwise NOT (~~)
http://stackoverflow.com/questions/784929/what-is-the-not-not-operator-in-javascript

  • Simon

    Thanks, useful !!

  • slmarsh

    Who likes !! jokes?! :facepalm:

  • https://englishextra.github.io/ englishextra

    I prefer:

    if (!!variable_name )

    instead of long:

    if (“undefined” !== typeof variable_name && variable_name)

Recommended

Learn Coding Online
Learn Web Development

Start learning web development and design for free with SitePoint Premium!

Get the latest in JavaScript, once a week, for free.