1

"" + {} evaluates to "[object Object]"

0 + {} evaluates to "0[object Object]"

However, + {} on its own evaluates to NaN, so it is being casted to a number. How comes that + {} gets casted to a string in the expression 0 + {}?

3
  • 1
    Because there's a difference between the unary and the binary + operators. Commented Aug 13, 2018 at 10:15
  • And, as with all these questions, the answer is: because it's defined like that in the specification. Commented Aug 13, 2018 at 10:17
  • 1
    To the 4 people who downvoted: what's actually wrong with my question? Commented Aug 13, 2018 at 11:57

2 Answers 2

3

In the latter case + is a unary operator which tries to convert {} in a Number but in the first case there is an addition happening and as default conversion from an object to string is [object Object] hence you are seeing the corresponding results.

Sign up to request clarification or add additional context in comments.

1 Comment

Just as a FYI, the antonym (opposite word) for 'latter' is 'former'. Generally, when latter is used, so is former and vice versa.
2

The difference is because, even though the two pluses look identical, they are in fact different operators.

In the former case, you have a binary +, meaning it has two operands (one on either side). As with many other languages, the binary + in JS has many functions depending on the types of the operands. Here, it does string concatenation, hence the result you get (the string representations of the two operands, joined together).

In the latter case, you have a unary +, meaning it only has one operand. In the JS specification, the unary plus' job is to coerce its operand into a number. Since that is not possible with an empty object, you get NaN instead.

2 Comments

Why does it do string concatenation in 0 + {} when it does number addition in 0 + {valueOf:()=>{return 5;}}? What rules does it follow to decide?
Object.prototype.valueOf is special. Check out the documentation. This function's job is to return a primitive representation of an object, defined by the user. Whenever a statement is evaluated that contains the object in a place where a primitive is expected, that function is invoked automatically and the returned value (in this case, the number 5) takes the object's place.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.