Joshua W
Joshua W

Reputation: 1133

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?

Upvotes: 5

Views: 912

Answers (2)

gdoron
gdoron

Reputation: 150313

You don't need to use !! inside an if expression. It's being used the convert the value to a Boolean, and the if does it by default.

var x = ""; // A falsy value
!x // true
!!x // false

if (x) === if (!!x)

Upvotes: 1

Jani Hartikainen
Jani Hartikainen

Reputation: 43273

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.

Upvotes: 7

Related Questions