Possible Duplicate:
What is the explanation for these bizarre JavaScript behaviours mentioned in the 'Wat' talk for CodeMash 2012?
Could someone explain to me how thees returning results can be different in javascript:
› {} + []
» 0
› [] + {}
» "[object Object]"
This is because the
{}in the code is not an object literal, but an empty block.It is parsed as:
Compare with
({}) + []which yields the same results as[] + {}; in this case the parenthesis force the{}to be treated/parsed “in an expression context”.There are a bunch of duplicates on SO about this particular dual-nature of
{}(as an expression or block?) but, finding them can be somewhat tricky ..I found https://meta.stackexchange.com/questions/83911/how-do-i-search-stackoverflow-for-at-keywords-like-private-or-synthesize on Meta, and using Symbolhound the “closest” duplicates I could find resolved around questions like this (that relate to the need to add parenthesis when “eval’ing JSON”) or this (where the use of constructs like “{} == false” is a syntax error).
If anyone knows a better way to search SO for this sort question, or has a link to such a duplicate handy ..