In the Chrome JavaScript console, why does wrapping the statement {} - 0
in parentheses change the returned value?
{} - 0 // Returns -0
({} - 0) // Returns NaN
It seems incredibly strange that wrapping a single statement in parentheses alters the contained value. What am I missing here?
There are two possible interpretations of the line {} - 0
:
{}; -0
, where {}
is interpreted as an empty block statement, and -
is the unary negation operator (so -0
is just "negative zero"). The value of this when evaluated is the value of the last statement, which is -0.({} - 0)
, where {}
is interpreted as an empty object, and -
is the subtraction operator (so 0
is subtracted from {}
).In your first line, this is ambiguous, so it will choose the first interpretation. In the second line, the first interpretation is invalid (as a block statement can never be part of an expression, which you're forcing with the parantheses).
{} - 0
: here {}
is just an empty block that does nothing, so -0
returned by the console.
({} - 0)
: here {}
is a part of expression and is converted to a number. There is no valueOf()
method defined in that empty object and, while converting to a number, it falls back to toString()
method which returns something like object Object
for {}
. Then this string object Object
is being converted into a number and gives NaN
since it is actually not a number. So, we've got
({} - 1)
-> ('object Object' - 1)
-> (NaN - 1)
and everything with NaN
gives NaN
. That's what you finally see in the console.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With