javascriptoperators

What does the !! 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?


Solution

  • 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