Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

{} - 0 VS ({} - 0) in JavaScript [duplicate]

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?

like image 469
Elliot Godzich Avatar asked Aug 11 '17 21:08

Elliot Godzich


2 Answers

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).

like image 59
Frxstrem Avatar answered Sep 22 '22 19:09

Frxstrem


{} - 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.

like image 37
curveball Avatar answered Sep 22 '22 19:09

curveball