-3

I stumbled across this the other day on reddit. The poster noted that

{} + ""

is equal to 0, while the similar

"" + {}

is equal to an empty [object Object].

Normal math rules tell me this is odd, but why is it this way?

hiybbprqag
  • 23
  • 5

1 Answers1

0

The token { at the beginning of a statement might mean the start of an object literal, or it might mean the start of a statement block. JavaScript assumes it's the latter, a statement block.

Thus

{} + ""

is just an empty statement block followed by the expression + "", which will be interpreted as 0 due to the semantics of the unary + operator.

In the other one, {} is not at the beginning of a statement, so it's unambiguously an (empty) object literal.

Pointy
  • 405,095
  • 59
  • 585
  • 614
  • Elect me president and I'll make it a law that anybody who talks about JavaScript "wat" stuff has to offer a complete explanation of every single thing. – Pointy Jun 01 '16 at 18:50
  • 2
    I'll elect you president if you immediately ban anybody who posts "wat" questions. – Jeremy Jun 01 '16 at 18:52