Possible Duplicate:
What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?
I know that when []
is coerced to a string it returns the empty string (""
), and when {}
is coerced to a string it returns "[object Object]"
.
When I run [] + {}
in my browser's Javascript console, it returns as I would expect:
>> [] + {} "[object Object]"
But when I run {} + []
, it returns a completely unexpected value:
>> {} + [] 0
What could be causing it to return 0
?
[] is falsy and '0' is string , js is not able to coerce them to convert the to type which can be compared . so false is returned . That document says it applies in a Boolean context. == is not a Boolean context.
-1, 0, and 1 in a comparison function are used to tell the caller how the first value should be sorted in relation to the second one. -1 means the first goes before the second. 1 means it goes after. 0 means they're equivalent.
So, what is the meaning of {} in JavaScript? In JavaScript, we use {} braces for creating an empty object. You can think of this as the basis for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array.
0 is an argument passed to void that does nothing, and returns nothing. JavaScript code (as seen above) can also be passed as arguments to the void method. This makes the link element run some code but it maintains the same page.
When there is a {
at the beginning of a statement, it will be interpreted as a block, which may contain zero or more statements. An block with no statements in it will have an empty continuation value.
In other words, in this case, {}
is interpreted as an empty code block.
The statement ends after the ending brace }
, which means that the next three characters +[]
comprise a statement of their own.
At the beginning of an expression or statement, +
is the unary plus operator, which coerces its operand to a number.
So +[]
is the same as Number([])
, which evaluates to 0
.
In short, {} + []
is an empty code block followed by an array coerced to a number.
All that said, if you evaluate {} + []
inside an expression, it will return what you expect:
>> ({} + []) "[object Object]"
Another interesting thing is that you cannot begin a statement with an object literal because the interpreter will try to parse it as a statement. Doing this
{ "object": "literal" };
will throw a syntax error.
Because the {}
is treated as a block. Thus your statement is actually:
{ //empty block here } +[] //0 same as Number([])
This is why this is invalid javascript:
eval('{hello: "world", key: "value"}') //Syntax error
You can add () to make it an expression (blocks cannot be used in an expression so it will be object initializer:
eval('({hello: "world", key: "value"})') //Object
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With