The use of the triple exclamation mark
JavascriptJavascript Problem Overview
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?
Javascript Solutions
Solution 1 - Javascript
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.
Solution 2 - Javascript
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.
Solution 3 - Javascript
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.
Solution 4 - Javascript
In JavaScript, it's a way to show that what you are evaluating is not a boolean but a truthy or falsy value.
So for truthy/falsy values you either use !!
or !!!
.
And for boolean values you either use !
or nothing.
This is simply for readability.