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?
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With