5

Possible Duplicate:
What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?

When I type

{} + []

in the Google Chrome JavaScript console, I get

0

as a result. However, when I type

Function("return {} + []")()

I get

"[object Object]"

as a result. I would think that both operations should return the same result, as one is simply a wrapper around the other. Why do they return different results?

Community
  • 1
  • 1
Markus Roth
  • 343
  • 2
  • 5
  • 12
  • 2
    The statement inside your function is different from the first statement. – Pointy Aug 13 '12 at 21:26
  • `[object Object]` is just effect of using `({}).toString()` - do you `alert` your function result or do `console.log`? – Setthase Aug 13 '12 at 21:27
  • 1
    `({}+[])` returns "[object Object]". As Mike explained below, it's the difference between a statement and an expression. – nnnnnn Aug 13 '12 at 21:38
  • 1
    http://stackoverflow.com/questions/11939044/why-does-return-0-in-javascript – some Aug 13 '12 at 22:22

1 Answers1

9

The core reason is that {} means a different thing in a statement context { statement0; statement1 } than in an expression context ({ "property": value, ... }).

 {} + []

is a block and a unary comparison operator so the same as

{}  // An empty block of statements.
(+ [])  // Use of prefix operator +.

The other is a use of the plus operator which when used with two objects concatenates them as in

return String({}) + String([])

Since Array.prototype.toString joins the array on commas, it is similar to

return String({}) + [].join(",")

which reduces to

return "[Object object]" + "";

and finally to

return "[Object object]"
Mike Samuel
  • 118,113
  • 30
  • 216
  • 245
  • Why is {} parsed differently in the two mentioned cases? – Markus Roth Aug 13 '12 at 21:42
  • @MarkusRoth It's because function returns are evaluated as expressions; in which case an empty `{}` is evaluated as an object. The other case the `{}` was treated as an empty code block. – Peter Aug 13 '12 at 21:52