What's the point of using double negation in Javascript?


Recently, while studying some code in javascript, I came across the following code:

return !!navigator.userAgent.match(/iPad/i);

I know that:

!true == false
!false == true

And consequently:

!!true == true
!!false == false

So I was in doubt: what is the logic of doing this type of operation?

asked by anonymous 14.08.2014 / 17:22

3 answers


This is a quick way to convert the result of an expression to a boolean value True / False (or in technical terms, providing typecast for boolean ), simplifying thus conditional evaluation processes.

There is a post on the original Stack Overflow that perfectly describes this behavior . The translation of the relevant part follows:


The first sign ! evaluates the expression, converting the logical value and   denying it.   The second sign ! reverses the value of the first.


In the documentation, regarding the logical operator : / p>      


Returns false if its single-operator can be converted to true ; otherwise, it returns true .


The following values are evaluated as "false":

  • false
  • NaN
  • undefined
  • null
  • "" (empty string)
  • 0
14.08.2014 / 17:29

Since the purpose of return !!navigator.userAgent.match(/iPad/i); is to find out whether the current device is an iPad or not, it is interesting / elegant that the function return is Boolean ( true or false ).

The problem is that by simply calling the navigator.userAgent.match(/iPad/i); function (without the double negation), the return will be null or ['iPad'] (or maybe something else) instead of true or false .

Using !! is a way to force the return of this match to be converted to a Boolean value, while maintaining the correct logical value for the target in question. In other words, ['iPad'] turns true and null false . =)

In stages it becomes clearer:

  • navigator.userAgent.match(/iPad/i); // ex: retorno ['iPad']
  • !navigator.userAgent.match(/iPad/i); // primeira negação, !['iPad'] == false
  • !!navigator.userAgent.match(/iPad/i); // segunda conversão, !false == true
  • 14.08.2014 / 17:40

    The double negation serves to make the return of the function more typesafe. It is a good technique to ensure that certain functions only return Boolean values, thus abstracting the user from the returns function that may not make sense.

    For example

    function isIpad() {
        return navigator.userAgent.match(/iPad/i);
    if ( isIpad() ) { ... }

    This code will work because if iPad is an array is returned (and this is true ) if it is not going to return null (which is evaluated as false ). But for the developer to see in the output of isIpad() null or ["iPad"] it escapes the semantics of "is" so the double negation forces the function isIpad () to return exclusively or false or true

    14.08.2014 / 20:00