JavaScript · Question 73
How does JavaScript convert objects to primitive values, and what role does Symbol.toPrimitive play?
Direct answer
Object-to-primitive conversion first allows a Symbol.toPrimitive method to decide the result; otherwise JavaScript falls back to ordinary conversion using valueOf() and toString() in an order influenced by the requested conversion hint.
Operations such as string interpolation, numeric arithmetic, and loose equality can require an object to become a primitive. If the object defines obj[Symbol.toPrimitive], JavaScript calls it with a hint such as "number", "string", or "default". The method must return a primitive value.
For example, an object can implement [Symbol.toPrimitive](hint) { return hint === "number" ? 42 : "answer"; }. Then +obj can produce 42 while `${obj}` can produce "answer". This is intentional customization of coercion, not operator overloading in the general sense.
- If
Symbol.toPrimitiveexists, it takes precedence over the ordinary fallback. - Ordinary conversion consults methods such as
valueOf()andtoString(); the exact preference depends on the hint. - Returning another object from
Symbol.toPrimitivecauses aTypeErrorbecause the conversion must produce a primitive.