javascriptbooleannegation

Double Not operator


I saw this line of code in a book:

!!(document.all && document.uniqueID);

Why is it necessary to use the double not operator? Do not the && operator already transform the result to a Boolean?


Solution

  • && will return the value of document.uniqueID (if document.all has any value other than '',false, null, undefined, 0, NaN) for document.all && document.uniqueID:

     for Example 45 === (true && 45) //true
    

    From mozilla.org.

    Logical AND (&&) expr1 && expr2 returns expr1 if it can be converted to false; otherwise, it returns expr2. Thus, when used with Boolean values, && returns true if both operands are true; otherwise, it returns false.

    So it is necessary to use !! to convert the above expression into Boolean.