The !
operator always returns either true
or false
, so assuming evaluation of x
completes normally, !!x
is a boolean value that is the equivalent of Boolean(x)
where Boolean
is the EcmaScript builtin function.
http://es5.github.com/#x11.4.9 says
11.4.9 Logical NOT Operator ( !
)
The production UnaryExpression : !
UnaryExpression is evaluated as follows:
- Let expr be the result of evaluating UnaryExpression.
- Let oldValue be ToBoolean(GetValue(expr)).
- If oldValue is
true
, return false
.
- Return
true
.
http://es5.github.com/#x9.2 explains how ToBoolean works
9.2 ToBoolean
The abstract operation ToBoolean converts its argument to a value of type Boolean according to Table 11:
Table 11 — ToBoolean Conversions
Argument Type Result
Undefined false
Null false
Boolean The result equals the input argument (no conversion).
Number The result is false if the argument is +0, −0, or NaN; otherwise the result is true.
String The result is false if the argument is the empty String (its length is zero); otherwise the result is true.
Object true
The above table explains most of your examples, but it may not be obvious why
console.log(boolCheck());
is false
. When you call a function with fewer actual arguments than formal parameters, the extra parameters have the value undefined
and, as the table above shows !!undefined
is false
.
are there any gotchas in doing : !!someValue
?
The intent is less clear than Boolean(someValue)
, but it will work consistently across platforms and most experienced Javascript devs will recognize it.