If I type in Chrome console
{} + {}
I get "[object Object][object Object]"
but if I add a semicolon the result is different:
{} + {};
I get NaN
I don't understand the difference though. First one makes sense, to me as the addition operator rules are the following:
- If at least one operand is an object, it is converted to a primitive value (string, number or boolean);
- After conversion, if at least one operand is string type, the second operand is converted to string and the concatenation is executed;
- In other case both operands are converted to numbers and arithmetic addition is executed.
Since both operands are object, they are converted to string. But what is going on in the second case?
If I assign a value (a = ...)
in both cases my variable will be a string. I tried to look for a specification of what Chrome console return when an expression is given, but didn't find one.
Weirdly enough adding a comment will return NaN
too :
{} + {} //comment
=> NaN
I know Javascript can be strange sometimes, but there is almost always a logical explanation. Here it seems to depend on how Chrome interprets it.
Firefox on the other hand returns NaN
for both cases, which I don't understand either.