0

Could you please explain why the results are different?

  1. ({} + {}) // = "[object Object][object Object]"
  2. {} + {} // = NaN

I understand that in both cases objects are converted to strings, but why in the second case the result is converted to a number?

Ezee
  • 4,214
  • 1
  • 14
  • 29

1 Answers1

2

From:

http://www.2ality.com/2012/01/object-plus-object.html

The problem is that JavaScript interprets the first {} as an empty code block and ignores it. The NaN is therefore computed by evaluating +{} (plus followed by the second {}). The plus you see here is not the binary addition operator, but a unary prefix operator that converts its operand to a number, in the same manner as Number()

...

Why is the first {} interpreted as a code block? Because the complete input is parsed as a statement and curly braces at the beginning of a statement are interpreted as starting a code block. Hence, you can fix things by forcing the input to be parsed as an expression:

({} + {})

'[object Object][object Object]'

Community
  • 1
  • 1
Andrea Casaccia
  • 4,802
  • 4
  • 29
  • 54