Javascript Double Not-Operator(!!)
In javascript Falsy and Truthy values are used all over the place.
For example the following values are always falsy:
""
(empty string)undefined
false
0
null
NaN
And any other value is truthy.
Since undefined and empty string are falsy values then we could replace this code below:
if typeof x !=== 'undefined' && x !=== ''
with a falsy/truthy verification:
if x
To set the result of falsy/thruthy verification to a variable is possible to use a double not-operator(!!
) which will force a type casting to Boolean.
;
Actually !!
is not a operator it is only the !
operator twice. The first !
will cast to boolean inverting the result. Then the second !
will invert again the value so it is the expected boolean value.
; // falsy
!x; // true (it is not what we want)
!!x; // false