{} - 0 Vs ({} - 0) In Javascript
Solution 1:
There are two possible interpretations of the line {} - 0
:
- It can be interpreted as
{}; -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. - It can be interpreted as
({} - 0)
, where{}
is interpreted as an empty object, and-
is the subtraction operator (so0
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).
Solution 2:
{} - 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.
Solution 3:
{} - 0
is interpreted: {} empty block statement
and - 0 negative zero
({} - 0)
all inside ()
is interpreted as an expression, empty object - 0 = NaN
Post a Comment for "{} - 0 Vs ({} - 0) In Javascript"