Object to Primitive: ToPrimitive Algorithm
You'll learn: How JavaScript decides which method to call when converting an object to a primitive value, and why adding two empty objects gives you a strange string.
The Conversion Order
When JavaScript needs to convert an object to a primitive value, it follows a specific algorithm called ToPrimitive. This algorithm has a "hint" that tells it what kind of value is preferred:
- "number" hint: Tries
valueOf()first, thentoString() - "string" hint: Tries
toString()first, thenvalueOf() - "default" hint: Usually behaves like "number"
Most arithmetic operations use the "number" hint, while explicit string operations use the "string" hint.
Why {} + {} Gives '[object Object][object Object]'
When you use the + operator with two objects, JavaScript must convert them to primitives:
- The
+operator gives a "default" hint (acts like "number") - JavaScript calls
valueOf()on each object - The default
valueOf()returns the object itself (not a primitive!) - JavaScript then falls back to
toString() - The default
toString()returns'[object Object]' - Now both sides are strings, so
+concatenates them - Result:
'[object Object][object Object]'
Think of it like asking someone for directions: first you ask if they know the route by car (valueOf), and if they don't, you ask for the walking directions (toString).
Key Takeaway: JavaScript's ToPrimitive algorithm tries valueOf() then toString() (or vice versa depending on context) when converting objects to primitives, which is why object addition produces string concatenation.