Skip to content Skip to sidebar Skip to footer

{} - 0 Vs ({} - 0) In Javascript

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 incred

Solution 1:

There are two possible interpretations of the line {} - 0:

  1. 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.
  2. It can be interpreted as ({} - 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).

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"