Sub topic 11
How Objects Become Primitives
This chapter assumes you already know the conversion rules for ToNumber and ToString on primitive values, and that you can define objects with methods. Operators such as *, +, and template literals work on primitives. When they receive an object, JavaScript first converts it to a primitive using an abstract operation called ToPrimitive.
The Hint
ToPrimitive takes a hint that says which kind of primitive the operation would prefer:
| Hint | Used by |
|---|---|
| `"number"` | Unary `+`, `-`, `*`, `/`, `Number()`, relational operators |
| `"string"` | Template literals, `String()`, property keys |
| `"default"` | Binary `+`, `==` |
The hint expresses a preference. It does not guarantee the result type. An object asked for a number can still return a string.
The Lookup Order
ToPrimitive goes through these steps in order:
- If the object has a
Symbol.toPrimitivemethod, call it with the hint. If it returns a primitive, use that value. Otherwise, throw aTypeError. - If there is no such method, apply the ordinary algorithm. With the
"string"hint, trytoString()first and thenvalueOf(). With the"number"or"default"hint, tryvalueOf()first and thentoString(). - The first method that returns a primitive wins. If both return objects, throw a
TypeError.
Seeing It Work
const temperature = {
[Symbol.toPrimitive](hint) {
if (hint === "number") return 21;
if (hint === "string") return "21°C";
return "default";
}
};
console.log(+temperature); // 21
console.log(`${temperature}`); // "21°C"
console.log(temperature + ""); // "default"
const price = {
valueOf() { return 9.99; },
toString() { return "$9.99"; }
};
console.log(price * 2); // 19.98: number hint calls valueOf first
console.log(`${price}`); // "$9.99": string hint calls toString first
console.log(price + ""); // "9.99": default hint tries valueOf firstWhy Plain Objects and Arrays Convert the Way They Do
Object.prototype.valueOf returns the object itself. That result is not a primitive, so ToPrimitive moves on to toString(). This is why {} becomes "[object Object]", and why [1, 2] becomes "1,2": Array.prototype.toString joins the elements with commas. An empty array becomes "", which explains Number([]) === 0.
Common Errors
- Returning an object from
Symbol.toPrimitive. This always throws aTypeError. The method gets no fallback. - Overriding only
toStringand expecting numeric behavior. The"number"hint still works, becausevalueOfreturns the object andtoStringis tried next. The result is then converted again with ToNumber. - Assuming
+uses the string hint. Binary+passes"default", so ordinary objects callvalueOffirst.
Exercise
Given const box = { valueOf() { return 4; }, toString() { return "7"; } }, what are box * 2, ${box}, and box + 1?
Show answer
box * 2 is 8, because the number hint calls valueOf first. ${box} is "7", because the string hint calls toString first. box + 1 is 5, because the default hint calls valueOf first, and 4 + 1 is 5.
Exercise
Why does String({}) return "[object Object]" even though the string hint tries toString first, and what would Number({}) return?
Show answer
String({}) returns "[object Object]" because toString on a plain object returns that string. Number({}) uses the number hint. valueOf returns the object itself, which is not a primitive, so ToPrimitive falls back to toString and gets "[object Object]". ToNumber then converts that string to NaN.