aga
aga

Reputation: 29434

The use of the triple exclamation mark

Looking through the source code of one of our projects, I've found some amount of places where we're using three exclamation marks in conditional statements, like so:

if (!!!someVar) {
    // ...
}

Now, I understand that this isn't some kind of rarely used operator, it's just three negations in a row, like !(!(!someVar))). I don't understand what's the use of it - in my opinion it can safely be replaced with single exclamation mark. Following are my attempts to find a case when !!!a isn't equal to !a (taken straight from the google chrome console):

var a = ''
""
!!!a === !a
true
a = 'string'
"string"
!!!a === !a
true
a = null
null
!!!a === !a
true
a = 12
12
!!!a === !a
true
a = {b: 1}
Object {b: 1}
!!!a.c === !a.c // a.c is undefined here
true
a = []
[]
!!!a === !a
true
a = [1,2]
[1, 2]
!!!a === !a
true

Am I missing some rare (or obvious) case?

Upvotes: 108

Views: 59353

Answers (4)

Zoidbergseasharp
Zoidbergseasharp

Reputation: 4538

Triple exclamations are sometimes used for readability.

They are used for showing that what you're evaluating is not a boolean, but some other truthy or falsy value.

So for truthy/falsy values you either use !! or !!!.

And for boolean values you either use ! or nothing.

So when you're reading the code, it gets a bit easier to tell whether this variable is a boolean or some other value.

Otherwise, logically, !!!a is same as !a.

Upvotes: 27

theGleep
theGleep

Reputation: 1187

Consider:

var x;
console.log(x == false);
console.log(!x, !x == true);
console.log(!!x, !!x == true, !!x == false);  

... the console output is:

false 
true true 
false false true

notice how, even though x is "falsey" in the first use, it is not the same as false.

But the second use (!x) has an actual boolean - but it's the opposite value.

So the third use (!!x) turns the "falsey" value into a true boolean.

...with that in mind, the third exclamation point makes a TRUE negation of the original value (a negation of the "true boolean" value).

ETA:

OMG! I can't believe I didn't notice that this is a TRIPLE exclamation point question! Even after it was specifically pointed out to me.

So, while my answer is hopefully useful to someone, I have to agree with the others who have posted that a triple-exclamation is functionally the same as a single.

Upvotes: 7

Filip
Filip

Reputation: 2344

It is the same as one exclamation mark. The key idea behind it is to improve visibility for the programmer. Compiler will optimize it as single '!' anyway.

Upvotes: 18

Sophiα2329
Sophiα2329

Reputation: 1741

There is no difference between !a and !!!a, since !!!a is just !!(!a) and because !a is a boolean, !!(!a) is just its double negation, therefore the same.

Upvotes: 148

Related Questions