Home javascript Double denial

Double denial

Author

Date

Category

How to understand double denial: !! (for example, in javascript)?


Answer 1, Authority 100%

In JavaScript, any value can be interpreted as boolean. (The rules for this interpretation are quite complex and not quite intuitive.)

If you specify any expression where boolean is expected (for example, inside the if ‘a), it is interpreted as Boolean, and that’s it. But if you want get the corresponding boolean (for example, to return it from a function or assign another variable), you need a trick that will force the system to interpret your expression in the Boolean context.

For this purpose, double negation is traditionally used: the first denial “requires” boolean context, so that the expression is interpreted as Boolean, and the second denial “cancels” the first.

from Documentation :

Decanion Operator: Returns False If its argument can be converted to True , otherwise returns True .


For reference: Values ​​that in Boolean context will be interpreted as False The essence of the following:

  • number 0.0
  • number NAN
  • undefined
  • null
  • empty string
  • And of course False

All other values ​​will be interpreted as True .

Example: if x – object or null , instead of

if (x! = NULL)
  RETURN TRUE;
ELSE.
  RETURN FALSE;

You can use elegant

return !! x;

About other languages: A similar trick is needed mainly in weakly typed languages ​​like JavaScript, in which the variable value can be true / false, and undefined, and the function, and object. The use of double denial ensures the absence of surprises in the behavior of the resulting object: its type is accurately boolean. However, I met this trick and in C++ in the context of the explicit conversion of the pointer in Bool .

Programmers, Start Your Engines!

Why spend time searching for the correct question and then entering your answer when you can find it in a second? That's what CompuTicket is all about! Here you'll find thousands of questions and answers from hundreds of computer languages.

Recent questions