Answers to {} - 0 VS ({} - 0) in JavaScript ( 3 )

  1. 2017-08-11 23:08

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

  2. 2017-08-11 23:08
    {} - 0
    

    is interpreted: {} empty block statement and - 0 negative zero

    ({} - 0)
    

    all inside () is interpreted as an expression, empty object - 0 = NaN

  3. 2017-08-11 23:08

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

Leave a reply to - {} - 0 VS ({} - 0) in JavaScript

◀ Go back