What does the following mean in javascript and How does it evaluate to a result true.
!!"false"
Would there by any need to use such an expression.
What does the following mean in javascript and How does it evaluate to a result true.
!!"false"
Would there by any need to use such an expression.
Every non-empty string is considered true. So when you double negate something that's true, you get true again.
Code like that can be used to get the boolean value from a non-boolean variable, for example.
That means not not a truely value string, so you'll end up with true
(boolean).
Ah, this one is tricky if you assume that "false" evaluates to boolean false. Know that, unless it's an empty string, "", that a string will always evaluate to true. So, you are basically saying, not not true. Double-negative cancels out, thus, true.
You should recall which things in Java are truthy and falsy–which items convert to true and false in logical contexts:
false
null
undefined
0
NaN
''
true
NaN
).Note that new Boolean(false)
is truthy. Don't wrap primitives.
Now the !
operator takes false
to true
and back. For any other value, it takes the logical interpretation converting to boolean
, and then flips it. So, !"false"
first interprets "false"
as true
since nonempty strings are truthy. Then, it computes !true
, and gets false
.
Using a second !
operator will then convert the false
to true
. Given a truthy argument x
, !!x
will be true
. Given a falsy argument y
, !!y
will be false
.
It is done to evaluate a non-boolean value as if was a boolean, any value will be evaluated as true except: undefined, null, 0, false or empty string ("").