1

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;
c00000fd
  • 20,994
  • 29
  • 177
  • 400
  • 1
    Yes. The not operator (`!`) always returns a Boolean. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_NOT_.28.21.29 – Felix Kling Sep 18 '14 at 05:23
  • 3
    No, if the operand doesn't exist, youl'll get an error instead. – Teemu Sep 18 '14 at 05:23
  • possible duplicate of [How can I convert a string to boolean in JavaScript?](http://stackoverflow.com/questions/263965/how-can-i-convert-a-string-to-boolean-in-javascript) – kornieff Sep 18 '14 at 05:29

2 Answers2

1

Shorthand used for converting anything to boolean type, same as

var bResult = Boolean(someVariable);

https://stackoverflow.com/a/264037/3094153

Community
  • 1
  • 1
kornieff
  • 2,389
  • 19
  • 29
1

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.

BatScream
  • 19,260
  • 4
  • 52
  • 68