Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS double exclamation -- is there any good reason to use it?

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?

like image 448
Steve Avatar asked Sep 19 '11 20:09

Steve


People also ask

Should you use double exclamation?

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.

What is the purpose of double exclamation?

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.


1 Answers

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

  1. Capturing the truthiness of the value
  2. Freeing up the original object for collection (should that be the final reference)
  3. Helps prevent later incorrect usages of an object with coercing equality (==). Doesn't prevent them all but forcing it down to a bool removes a set of scenarios.
like image 186
JaredPar Avatar answered Sep 21 '22 02:09

JaredPar