{} + [] in Javascript

Possible duplicate:
What is the explanation for these fancy JavaScript actions mentioned in the Wat talk for CodeMash 2012?

When i type

{} + [] 

in the google chrome javascript console i get

 0 

. However, when I print

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

I get

 "[object Object]" 

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

+4
source share
1 answer

The main reason is that {} means another thing in the context of the { statement0; statement1 } { statement0; statement1 } than in the context of the expression ({ "property": value, ... }) .

  {} + [] 

- block and unary comparison operator, same as

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

Another is the use of the plus operator, which when used with two objects combines them, as in

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

Since Array.prototype.toString array, it looks like

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

which boils down to

 return "[Object object]" + ""; 

and finally to

 return "[Object object]" 
+9
source

All Articles