Course contentsShow
← JavaScript
Lesson 289 of 2,7238. Type CoercionFree lesson

Object to Primitive: ToPrimitive Algorithm

Understanding valueOf and toString order, and why {} + {} gives '[object Object][object Object]'.

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, then toString()
  • "string" hint: Tries toString() first, then valueOf()
  • "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:

  1. The + operator gives a "default" hint (acts like "number")
  2. JavaScript calls valueOf() on each object
  3. The default valueOf() returns the object itself (not a primitive!)
  4. JavaScript then falls back to toString()
  5. The default toString() returns '[object Object]'
  6. Now both sides are strings, so + concatenates them
  7. 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.