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?
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
The other is a use of the plus operator which when used with two objects concatenates them as in
Since
Array.prototype.toStringjoins the array on commas, it is similar towhich reduces to
and finally to