Why does !new Boolean(false) equals false in JavaScript?
Solution 1:
new Boolean(false)
returns an object. All objects (except document.all
in browsers) are truthy.
As a result, !
of any object will always be false
.
To prove it to yourself, you can run this in your JavaScript console:
(typeof new Boolean(false)) // "object"
Also, you can use the strict equality operator ===
to confirm that new Boolean(false)
isn’t really false
:
new Boolean(false) === false // false
Incidentally, calling the Boolean
function as a function—without the new
—actually does return a primitive:
!Boolean(false) // true
(typeof Boolean(false)) // "boolean"
Solution 2:
Because new Boolean
returns an object as stated here.
The !
is defined as follows:
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
, returnfalse
.Return
true
.
and:
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
...
Object -
true
So, it is an object, thus ToBoolean
returns true
, hence !
returns false
.