In the test I met this question, answered "no" because I believe that double negative should return the same value, but the correct answer is yes, tell me why.

    2 answers 2

    To begin, I will give a little theory.

    In fact, in JavaScript, logical operators || and && work in a special way.

    Operator || returns the first operand whose value can be coerced to true . If both operands are logically false , then the operator || will return the last value .

     console.log('foo' || false); // 'foo' console.log(null || 'bar'); // 'bar' console.log(false || 1); // 1 console.log(false || null); // null 

    This allows everyone to use the well-known well-known hack with the default variable value:

     function f(arg) { var a = arg || 0; // ... } 

    The && operator returns the first of the operands whose value is reduced to a logical false . If both operands are true , then the && operator returns the last operand .

     console.log(true && []); // [] console.log(null && 'foo'); // null console.log(0 && 'foo'); // 0 console.log('foo' && 'bar'); // 'bar' 

    As for the design !! , it is used to explicitly cast the operand to a logical type:

     console.log(!!'foo'); // true console.log(!!''); // false console.log(!!0); // false console.log(!!1); // true 

    Let's return to your question.

    As you might guess, the difference between the expressions

     !!(a && b); // (1) (a && b); // (2) 

    is in the type of the return value. If both variables a and b both of logical type, then these expressions are equivalent. In the general case, the type of the result of expression (2) is determined by the type of the operands, while expression (1) always returns the value of a boolean type.

      Probably because in the case of !! (a && b) there is a conversion to boolean. And in the case of (a && b) does not occur.