"" + {} 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 + {}?
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.
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.
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.
+operators.