I stumbled across this the other day on reddit. The poster noted that
{} + ""
is equal to 0
, while the similar
"" + {}
is equal to an empty [object Object]
.
Normal math rules tell me this is odd, but why is it this way?
I stumbled across this the other day on reddit. The poster noted that
{} + ""
is equal to 0
, while the similar
"" + {}
is equal to an empty [object Object]
.
Normal math rules tell me this is odd, but why is it this way?
The token {
at the beginning of a statement might mean the start of an object literal, or it might mean the start of a statement block. JavaScript assumes it's the latter, a statement block.
Thus
{} + ""
is just an empty statement block followed by the expression + ""
, which will be interpreted as 0
due to the semantics of the unary +
operator.
In the other one, {}
is not at the beginning of a statement, so it's unambiguously an (empty) object literal.