Sub topic 12
How Objects Become Primitives
This chapter assumes you already know the ToNumber and ToString rules from the previous chapters. It also assumes you know that objects are compared by reference. Operators such as -, *, and < only work on primitives, and so do template literals. When you give one of them an object, JavaScript first runs an internal step called ToPrimitive. This chapter covers that step: the order in which it calls methods, how the hint steers it, and the cases where it throws.
Where ToPrimitive Fits
ToPrimitive does not finish the conversion. It turns an object into some primitive, and then the usual ToNumber or ToString rules run on that result. For example, Number([5]) first gets "5" from the array and then converts "5" to 5.
There is one important exception. ToBoolean never calls ToPrimitive. Every object is truthy, so if (obj) never runs your valueOf or toString.
The Hint
The caller passes ToPrimitive a hint, which says what kind of primitive it would prefer. The hint is one of "number", "string", or "default".
| Context | Hint |
|---|---|
| `Number(x)`, unary `+x`, `-`, `*`, `/`, `%`, `**` | `"number"` |
| `<`, `>`, `<=`, `>=` | `"number"` |
| `String(x)`, `` `${x}` `` | `"string"` |
| Using an object as a property key, `obj[x]` | `"string"` |
| Binary `+`, `==` against a primitive | `"default"` |
The hint is only a preference. Nothing forces "number" to produce a number. If valueOf returns a string, the string is used, and ToNumber then converts it.
The Algorithm
ToPrimitive checks the object for a Symbol.toPrimitive method. If the method exists, ToPrimitive calls it with the hint string, and that method alone decides the result. If it does not exist, ToPrimitive falls back to the ordinary algorithm:
- Treat a
"default"hint as"number". - For
"number", tryvalueOf, thentoString. - For
"string", trytoString, thenvalueOf. - Use the first result that is a primitive. A method that is missing or returns an object is skipped.
- If no method produced a primitive, throw a
TypeError.
Watching the Order
Logging inside the methods shows which one runs, and in what order:
const traced = {
valueOf() {
console.log("valueOf called");
return {}; // not a primitive, so it gets skipped
},
toString() {
console.log("toString called");
return "7";
}
};
console.log(traced * 2);
// valueOf called
// toString called
// 14 ("7" then goes through ToNumber)
console.log(`${traced}`);
// toString called
// 7For traced * 2, valueOf runs first but returns an object, so ToPrimitive moves on to toString. The template literal asks for a string, so toString runs first and succeeds, and valueOf is never called.
Symbol.toPrimitive Takes Full Control
When an object defines Symbol.toPrimitive, JavaScript ignores valueOf and toString for this conversion:
const temperature = {
[Symbol.toPrimitive](hint) {
if (hint === "number") return 21;
if (hint === "string") return "21°C";
return "default";
},
valueOf() { return 999; } // never used by ToPrimitive
};
console.log(+temperature); // 21
console.log(`${temperature}`); // "21°C"
console.log(temperature + ""); // "default"This is the only way to tell the "default" hint apart from "number". With ordinary valueOf and toString, the two hints behave the same.
What Built-in Objects Do
Plain objects and arrays inherit Object.prototype.valueOf, which returns the object itself. ToPrimitive skips that result, so for these objects toString effectively always supplies the value.
console.log(String({})); // "[object Object]"
console.log(+[]); // 0 ([] -> "" -> 0)
console.log(+[5]); // 5 ([5] -> "5" -> 5)
console.log(+[1, 2]); // NaN ([1, 2] -> "1,2" -> NaN)
console.log([1, 2] + [3]); // "1,23"
console.log({} * 2); // NaN ("[object Object]" -> NaN)Date is the main exception. Date.prototype[Symbol.toPrimitive] treats the "default" hint as "string", so + concatenates while - subtracts:
const epoch = new Date(0);
console.log(epoch - 0); // 0 (number hint, valueOf gives milliseconds)
console.log(typeof (epoch + 1)); // "string" (default hint acts like string)
console.log(+epoch); // 0Wrapper objects such as new Number(5) return their primitive from valueOf, so new Number(5) + 1 is 6.
Failure Modes
Conversion throws a TypeError when no primitive can be produced. This happens in three situations:
- An object has no
valueOfortoStringat all, such as one made withObject.create(null). - Both methods return objects.
Symbol.toPrimitivereturns an object.
const bare = Object.create(null);
try {
`${bare}`;
} catch (e) {
console.log(e instanceof TypeError); // true
}
const stubborn = {
valueOf() { return {}; },
toString() { return []; }
};
try {
stubborn + 1;
} catch (e) {
console.log(e.message); // "Cannot convert object to primitive value" (V8 wording)
}Objects with a null prototype often come from dictionary-style code and some parsing libraries. If you log one with ` value: ${obj} `, your code will throw instead of printing.
Design Guidance
- Define
Symbol.toPrimitiveonly when the three hints really need different results. For a value type such asMoney, avalueOfthat returns a number plus atoStringthat returns a label is usually enough. - Never write conversion methods with side effects. They can run from places that are hard to spot, such as
==, property keys, and+. - Prefer explicit methods such as
toCents()orformat()over relying on conversion. Readers of the code can see exactly what happens.
Exercise
Given const box = { valueOf() { return "3"; }, toString() { return "box"; } }, what do box * 2, ${box}, and box + 1 evaluate to?
Show answer
box * 2 is 6: the number hint calls valueOf, which gives "3", and ToNumber turns it into 3. ${box} is "box", because the string hint calls toString first. box + 1 is "31": the default hint acts like number, so valueOf gives the string "3", and + concatenates because one operand is a string.
Exercise
Why does new Date(0) + 1 produce a string while new Date(0) - 1 produces -1?
Show answer
Date defines Symbol.toPrimitive and treats the "default" hint as "string". Binary + passes "default", so the date becomes a date string and + concatenates. Subtraction passes "number", so the date becomes 0 milliseconds, and 0 - 1 is -1.
Exercise
An object defines Symbol.toPrimitive that returns { n: 1 }, plus a valueOf that returns 5. What does +obj do?
Show answer
It throws a TypeError. When Symbol.toPrimitive exists, its result is final. Because that result is an object, ToPrimitive throws and never falls back to valueOf.