Reputation: 22327
Pardon me asking (I'm coming from the world of C/C++)
I'm curious if the following line will always set bResult
to be either true
or false
in JavaScript?
var bResult = !!someVariable;
Upvotes: 1
Views: 129
Reputation: 19700
According to ECMAScript Language Specification
,
The production UnaryExpression : ! UnaryExpression is evaluated as follows:
Let oldValue be ToBoolean(GetValue(expr)).
In case of var bResult = !!someVariable;
, the first logical Not operator is evaluated
oldvalue = !(ToBoolean(value of someVariable))
See the table below for how different datatypes are converted to to Boolean. So based on the type and value of 'someVariable' the conversion would take place.
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
If oldValue is true, return false. Return true.
This completes evaluation of the first logical NOT operator,
bResult = !(oldValue)
// the second logical NOT operator is evaluated again in the same manner and the result is obtained.
So the result depends on the data type and the value of 'somevariable', and it is not a trick.
Upvotes: 1
Reputation: 2557
Shorthand used for converting anything to boolean type, same as
var bResult = Boolean(someVariable);
https://stackoverflow.com/a/264037/3094153
Upvotes: 1