I've been debating this topic with a co-worker for about a week. I'm very much a fan of shorthand code, using ternaries, etc., wherever I can. Lately, he's been picking on me about my use of double exclamations. After running numerous tests, I'm beginning to agree with him... double exclamations may not be wise to use in my code. Consider this:
var myvar = "Hello";
return (!!myvar ? "Var is set" : "Var is not set");
The above example works as expected. However, if we are checking against a variable that may return undefined, we get an error, especially in IE7. We get our expected result, however, if we run this in our console:
if(randomvar) alert('Works');
Using this approach, if the variable is undefined, it fails silently. This makes me question the use of double exclamations altogether. Is there a situation that actually makes this operator beneficial?
Use the number of exclamation points that's in your heart. Language is supposed to help you communicate what you mean, so if you need two exclamation points for an extra-emphatic opinion and 27 for an announcement to your brother about your promotion, go for it.
The double exclamation point converts any object to a boolean value. To put it short, the double exclamation operator is not an actual operator. Instead, it's a chain of two not operators. The double-not operator converts an object into the boolean value it would be in a boolean context.
There is a valid use for !!
in javascript. It's an expression which will take a value and convert to either the boolean true
or false
. It essentially coerces the current state into a boolean.
This is good for both
==
). Doesn't prevent them all but forcing it down to a bool removes a set of scenarios. 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