What does the !! (double exclamation mark) operator do in JavaScript?

I saw this code:

this.vertical = vertical !== undefined ? !!vertical : this.vertical;

It seems to be using !! as an operator, which I don't recognize. What does it do?

重點答案

3.7k採納 by stevehipwell 原文 ↗

It converts Object to boolean. If it was falsy (e.g., 0, null, undefined, etc.), it would be false, otherwise, true.

!object  // Inverted Boolean
!!object // Noninverted Boolean, so true Boolean representation

So !! is not an operator; it's just the ! operator twice.

It is generally simpler to do:

Boolean(object) // Boolean

Real World Example "Test IE version":

const isIE8 = !! navigator.userAgent.match(/MSIE 8.0/);
console.log(isIE8); // Returns true or false

If you ⇒

console.log(navigator.userAgent.match(/MSIE 8.0/));
// Returns either an Array or null

But if you ⇒

console.log(!!navigator.userAgent.match(/MSIE 8.0/));
// Returns either true or false

It's a horribly obscure way to do a type conversion.

! means NOT. So !true is false, and !false is true. !0 is true, and !1 is false.

So you're converting a value to a Boolean, inverting it, and then inverting it again.

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

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

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

    // Or just
    val.enabled = Boolean(userId);

Note: the middle two expressions aren't exactly equivalent to the first expression when it comes to some edge cases (when userId is [], for example) due to the way the != operator works and what values are considered truthy.

!!expr (two ! operators followed by an expression) returns the primitive true or false depending on the truthiness of the expression.

It makes sense when used on non-boolean expressions. Some examples:

Note: the Boolean function produces the exact same results, and it is more readable.

          !!false // false
           !!true // true

              !!0 // false
!!parseInt("foo") // false — NaN is falsy
              !!1 // true
             !!-1 // true  — negative number is truthy
          !!(1/0) // true  — Infinity 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 value is falsy
      !!undefined // false — undefined primitive is falsy
           !!null // false — null is falsy

             !!{} // true  — an (empty) object is truthy
             !![] // true  — an (empty) array is truthy