What is the difference between if(!!condition) and if(condition)
I often see code that uses !!condition
as opposed to just the regular condition. I.e.:
if(!!value){
doSomething();
}
versus:
if(value){
doSomething();
}
What is the funcational difference, if there is one? Is one superior to the other? What, if any, are the conditions for picking to use one versus the other?
Technically nothing. The double bang !!
type converts value
to a boolean - something the if statement does when it evaluates value
anyway.
In the code you have posted, the !!
is useless and serves no purpose.
This is just a more explicit way to test the "truthiness" of a value.
The following will "cast" value
to a boolean.
!!(value)
For example, a non-empty string
!!"a" // true
Another example with an empty string
!!"" // false
However, if you simply test a value directly using
if (value) // ...
then the following values are false
in JavaScript
0
-0
null
-
""
(empty string) false
undefined
NaN
everything else is true