0

While playing around in Chrome's dev console, I noticed something that I don't understand:

  • ({})+"" evaluates to "[object Object]", as I expected
  • {}+"" evaluates to 0 (number)

Replacing {} with {foo:"bar"} in either expression doesn't change the result, so it does seem to be being parsed as an object literal. Replacing "" with "42" yields 42, and replacing it with "foo" yields NaN.

What's going on here?

qxz
  • 3,814
  • 1
  • 14
  • 29

1 Answers1

1

The context of the grammar changes.

({}) is an object literal expression evaluating to a new object so the code is effectively anObject+"". The parenthesis are defining here as they cause the code to be parsed as "(..some expression..)".

{}+"" is parsed as {};+"" since the {} are parsed as an empty block (as opposed to an object literal). This makes the code equivalent to +"" which yields 0.

{foo:"bar"} is parsed as block, with a label ("foo") to the singular expression "bar". There is no object literal.

Some (useful) ways where {..} will be parsed as an object literal expression:

z = {..}
({..})
f({..})
return {..}
user2864740
  • 60,010
  • 15
  • 145
  • 220