Sub topic 9
Controlling Coercion with Symbol.toPrimitive
This chapter assumes you know how JavaScript coerces values in expressions like +x, a + b, and template literals. It also assumes you have read the earlier chapter on well-known symbols. The focus here is one hook: Symbol.toPrimitive, which decides what an object turns into when the language needs a primitive.
The default behavior you are replacing
When an object appears where a primitive is required, JavaScript runs an internal step called ToPrimitive. If the object has no Symbol.toPrimitive method, the engine falls back to valueOf() and toString():
- With a string hint, it tries
toString()first, thenvalueOf(). - With any other hint, it tries
valueOf()first, thentoString().
Spreading that logic across two methods makes the behavior hard to predict. A single Symbol.toPrimitive method takes priority over both and receives the hint directly.
The three hints
The method receives one argument, the hint, which is always one of three strings:
| Hint | Triggered by |
|---|---|
| `'number'` | unary `+`, `Number(obj)`, `-`, `*`, `/`, `<`, `>` |
| `'string'` | template literals, `String(obj)`, using the object as a property key |
| `'default'` | binary `+`, loose equality `==` against a primitive |
The 'default' hint exists because binary + can't tell whether you mean addition or concatenation.
A worked example
const temperature = {
celsius: 21,
[Symbol.toPrimitive](hint) {
if (hint === 'string') return `${this.celsius} C`;
return this.celsius; // 'number' and 'default' hints
}
};
console.log(+temperature); // 21 (number)
console.log(`${temperature}`); // "21 C" (string)
console.log(String(temperature)); // "21 C" (string)
console.log(temperature + 1); // 22 (default)
console.log(temperature > 20); // true (number)
console.log(temperature == 21); // true (default)
console.log(temperature + ''); // "21" (default, not "21 C")Look at the last line. temperature + '' and ` ${temperature} look like the same thing, but they send different hints. Concatenation with + uses 'default', so the method returns 21, and only after that does +` join it with the empty string.
Common errors
Returning an object
The method must return a primitive. If it returns an object, JavaScript throws instead of trying again:
const broken = {
[Symbol.toPrimitive]() {
return {};
}
};
try {
console.log(+broken);
} catch (e) {
console.log(e instanceof TypeError); // true
}Using an arrow function
this inside an arrow function does not refer to the object, so this.celsius comes back undefined. Use method syntax, as in the example above.
Ignoring `'default'`
If you only handle 'number' and 'string' and let 'default' fall through to undefined, then obj + 1 gives NaN. Always decide what 'default' should mean. Built-in Date treats it as 'string', which is why new Date() + 1 produces a string. Most numeric-like objects treat it as 'number'.
Exercise
Given the temperature object above, what do temperature * 2 and [temperature].join('') produce, and which hint does each one use?
Show answer
temperature * 2 uses the 'number' hint and gives 42. [temperature].join('') converts each element with ToString, which uses the 'string' hint, so it gives "21 C".
Exercise
Write a money object with cents: 1999 that returns 1999 for numeric contexts and "$19.99" for string contexts, and throws a TypeError for the 'default' hint.
Show answer
const money = { cents: 1999, [Symbol.toPrimitive](hint) { if (hint === 'number') return this.cents; if (hint === 'string') return $${(this.cents / 100).toFixed(2)}; throw new TypeError('Ambiguous conversion of money'); } }; Then +money is 1999, ${money} is "$19.99", and money + 1 throws.