Search code examples
javascripttype-conversionnot-operator

Double not (!!) vs type coercion in JavaScript


Is there any advantage, except indicating an explicit conversion, to using a double not operator in JavaScript? It often seems that these days, people like to check for existence of new APIs using the double not, but I have never, ever read any advantage to it.

if(!!window.File)
    // The File API is supported.
else
    // Your browser sucks.

The one thing that I have read is that it is a concise, obscure way to type cast to Boolean, however, when used in this context the object will be auto coerced to Boolean anyway since we are checking to see if it is defined.

In short, why do people do two Boolean operations on top of the engine's?


Solution

  • I don't really see any reason to do it in context like you present. It will not affect the result in any way.

    The only time I'd see this as a good idea is if you're building a function which is supposed to return a bool value, and you need to cast it from some other value, eg...

    function isNotFalsy(val) { return !!val; }
    

    The example may be a bit forced, but you get the idea. You would always want to make sure the return value is of the type the user would expect.