3

I have tested the code:

{}+{} = NaN;
({}+{}) = "[object Object][object Object]";

Why does adding the () change the result?

xdumaine
  • 10,096
  • 6
  • 62
  • 103
goodMan
  • 69
  • 4

2 Answers2

8

{}+{} is a block followed by an expression. The first {} is the block (like the kind you attach to an if statement), the +{} is the expression. The first {} is a block because when the parser is looking for a statement and sees {, it interprets it as the opening of a block. That block, being empty, does nothing. Having processed the block, the parser sees the + and reads it as a unary +. That shifts the parser into handling an expression. In an expression, a { starts an object initializer instead of a block, so the {} is an object initializer. The object initializer creates an object, which + then tries to coerce to a number, getting NaN.

In ({}+{}), the opening ( shifts the parser into the mode where it's expecting an expression, not a statement. So the () contains two object initializers with a binary + (e.g., the "addition" operator, which can be arithmetic or string concatenation) between them. The binary + operator will attempt to add or concatenate depending on its operands. It coerces its operands to primitives, and in the case of {}, they each become the string "[object Object]". So you end up with "[object Object][object Object]", the result of concatenating them.

T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
1

Because of ambiguity. {} is an object but also a block boundary. Without () it is interpreted as the latter.

freakish
  • 54,167
  • 9
  • 132
  • 169