Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

double not (!!) vs type coercion in JavaScript [duplicate]

Is there any advantage, except indicating an explicit conversion, to using a double not operator in JavaScript? It oft' 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 anyways 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?

like image 522
Joshua W Avatar asked Jun 10 '12 20:06

Joshua W


People also ask

What is the difference between == and which one allows for type coercion?

For comparing these two values we are using double equal sign (==), this equality comparison is known as abstract equality comparison. Abstract comparison is done using type coercion means JavaScript will try to automatically convert type to produce result.

What are the different types of coercion?

And still there are only three types of conversion: numeric, string and boolean. coerced to true , no matter if an object or an array is empty or not. Objects are converted to primitives via the internal [[ToPrimitive]] method, which is responsible for both numeric and string conversion.

Which operator stops type coercion in JavaScript?

To explicitly coerce a value to a string in JavaScript we can use the String() function. To implicitly coerce a value to a string, we can use the + operator with any operand that is a string.

What is the use of double exclamation in JavaScript?

If you have ever noticed a double exclamation mark (!!) in someone's JavaScript code you may be curious what it's for and what it does. It's really simple: it's short way to cast a variable to be a boolean (true or false) value.


1 Answers

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.

like image 115
Jani Hartikainen Avatar answered Sep 22 '22 19:09

Jani Hartikainen