!! operator is obviously useful as it forces to check something that's not a boolean as a Boolean - that's for "True" conditions.
But what about false? Do you need to use !!!?
!! operator is obviously useful as it forces to check something that's not a boolean as a Boolean - that's for "True" conditions.
But what about false? Do you need to use !!!?
One !
would be enough :)
!1 // false
!0 // true
!!
is not an operator in itself; it is merely a way of using JavaScript's logical NOT (!
) operator.
To convert x
to a boolean, !!x
works because when you negate a boolean twice, you get the original boolean, and !x
converts x
to a boolean before negating it.
Likewise, !!!x
converts x
to a boolean and negates it three times, which is equivalent to negating it only once. So you can use !x
instead of !!!x
.
that's for "True" conditions.
No, it's for any value. !!
will convert any value in it's equivalent Boolean value.
Why? Because the not operator simply returns the opposite Boolean value. So
0 // is falsy
!0 // -> true
!!0 // -> false
'foo' // is truthy
!'foo' // -> false
!!'foo' // -> true
Any additional application will just toggle the value again. Thus !!!
is equivalent to !
and !!!!
is equivalent to !!
and so on.
var boolCheck = 0;
boolCheck //0
!boolCheck //true
!!boolCheck //false
!!!boolCheck //true - again
Same thing here:
var boolCheck = 1;
boolCheck //1
!boolCheck //false
!!boolCheck //true
!!!boolCheck //false - again
There is no reason to use this ( !!! ), it is a tautology. !! is useful when:
This answers your question perfectly https://stackoverflow.com/a/264037/1561922
!!!x is probably inversing a boolean conversion !!x:
var myBool = Boolean("false"); // == true
var myBool = !!"false"; // == true
"Any string which isn't empty will evaluate to true"
So !!!"false"; // == false
This question is NOT a joke. Node.js (downloaded 5 days ago) uses this in Assert.js for example:
function ok(value, message) {
if (!!!value) fail(value, true, message, '==', assert.ok);
}
assert.ok = ok;
EDIT: I think they did it for code readability reasons out of habit, because !value already suffices.
EDIT: Node changed it. I have no idea why my version of Node.js that was downloaded 5 days ago is still with the !!!value instead of the !value in GitHub.
EDIT: This is the reason why.