Sub topic 9
Controlling Coercion with Symbol.toPrimitive
This chapter assumes you know JavaScript's primitive types, how valueOf and toString work on ordinary objects, and how computed property names and class methods are written. Earlier chapters introduced well-known symbols as hooks into the language. This chapter covers one of them in detail: Symbol.toPrimitive. You define it to decide what your object becomes when JavaScript needs a primitive value.
The Working Model
Many operators need primitives, not objects. These include arithmetic, string concatenation, template literals, loose equality, and comparisons. When one of them receives an object, the engine runs an internal operation called ToPrimitive. ToPrimitive first looks for a method stored under Symbol.toPrimitive. If the method exists, the engine calls it with one string argument, called the hint, which says what kind of value the context prefers:
| Hint | Meaning |
|---|---|
| `"number"` | The context wants a number, as in math or comparisons |
| `"string"` | The context wants a string, as in template literals or `String()` |
| `"default"` | The context could use either one, as in binary `+` or `==` |
Your method can return any primitive it likes. The engine then applies the conversion it actually needs. If the hint is "number" and you return "5", the engine still turns that into the number 5.
Which Operations Send Which Hint
The hint depends on the operation, not on the other operand. Predicting it is the hardest part, so the most reliable way to learn it is to watch the hints arrive:
const seen = [];
const probe = {
[Symbol.toPrimitive](hint) {
seen.push(hint);
return hint === 'number' ? 42 : 'probe';
}
};
const record = (label, fn) => {
seen.length = 0;
const result = fn();
console.log(label.padEnd(16), seen[0].padEnd(8), result);
};
record('+probe', () => +probe); // number 42
record('probe * 2', () => probe * 2); // number 84
record('probe < 100', () => probe < 100); // number true
record('Number(probe)', () => Number(probe)); // number 42
record('Math.max(probe)', () => Math.max(probe)); // number 42
record('`${probe}`', () => `${probe}`); // string probe
record('String(probe)', () => String(probe)); // string probe
record('obj[probe]', () => ({ probe: 'key!' })[probe]); // string key!
record('probe + ""', () => probe + ''); // default probe
record('probe == "probe"', () => probe == 'probe'); // default trueHere are the rules in one table:
| Operation | Hint |
|---|---|
| Unary `+`, `-`, `*`, `/`, `%`, `**`, bitwise operators | `"number"` |
| `<`, `>`, `<=`, `>=` | `"number"` |
| `Number(x)`, `Math.*` functions | `"number"` |
| Template literal `${x}`, `String(x)` | `"string"` |
| Using an object as a property key, `obj[x]` | `"string"` |
| Binary `+` | `"default"` |
| `==` and `!=` against a primitive | `"default"` |
| `===`, `!==` | No conversion at all |
A Worked Example: A Money Type
Here is a realistic use. An amount stored in integer cents should act as a number in math and display nicely in text:
class Money {
constructor(cents, currency = 'USD') {
this.cents = cents;
this.currency = currency;
}
[Symbol.toPrimitive](hint) {
const amount = this.cents / 100;
if (hint === 'string') {
return `${amount.toFixed(2)} ${this.currency}`;
}
return amount; // 'number' and 'default'
}
}
const price = new Money(1999);
const tax = new Money(160);
console.log(`Price: ${price}`); // "Price: 19.99 USD"
console.log(String(tax)); // "1.60 USD"
console.log(price + tax); // 21.59
console.log(price > tax); // true
console.log(price * 2); // 39.98
console.log(price + ' total'); // "19.99 total"The last line shows the design choice behind "default". Concatenation gets the number 19.99, so the currency is dropped and you get "19.99 total" instead of "19.99 USD total". Making "default" return the number keeps price + tax working as addition. If you want text, use a template literal and you get the formatted string. No answer fits every type. Choose the "default" behavior that makes + least surprising for your type, and document it.
The Fallback: valueOf and toString
If an object has no Symbol.toPrimitive, the engine runs a fallback the specification calls OrdinaryToPrimitive. For the "string" hint it tries toString() first, then valueOf(). For "number" and "default" it tries valueOf() first, then toString(). It uses the first primitive result. If neither method returns a primitive, it throws a TypeError.
const legacy = {
valueOf() { return 10; },
toString() { return 'ten'; }
};
console.log(legacy + 1); // 11 (default: valueOf first)
console.log(`${legacy}`); // "ten" (string: toString first)
console.log(legacy * 3); // 30
const both = {
[Symbol.toPrimitive]() { return 'from symbol'; },
valueOf() { return 10; },
toString() { return 'ten'; }
};
console.log(both + ''); // "from symbol"
console.log(`${both}`); // "from symbol"When Symbol.toPrimitive exists, it takes over completely. The engine never calls valueOf or toString during coercion, even if your method returns something odd. The main advantage over the fallback is that you receive the hint directly. With valueOf and toString alone, your object can't tell "default" apart from "number".
Common Errors
Returning an object
The method must return a primitive. Returning an object, even this, throws a TypeError. The engine doesn't fall back to valueOf:
const bad = {
[Symbol.toPrimitive]() { return {}; },
valueOf() { return 1; }
};
try {
console.log(+bad);
} catch (e) {
console.log(e instanceof TypeError); // true
}Storing something that isn't a function
If the property holds undefined or null, the engine treats it as missing and uses the fallback. Any other non-callable value throws:
const fallback = { [Symbol.toPrimitive]: null, valueOf() { return 7; } };
console.log(fallback + 1); // 8
const broken = { [Symbol.toPrimitive]: 42 };
try {
console.log(`${broken}`);
} catch (e) {
console.log(e instanceof TypeError); // true
}Using an arrow function
Arrow functions don't get their own this. A method written as an arrow function reads this from the surrounding scope, not from the object:
const wrong = {
celsius: 21,
[Symbol.toPrimitive]: () => this?.celsius
};
console.log(+wrong); // NaN, because `this` isn't the object
const right = {
celsius: 21,
[Symbol.toPrimitive]() { return this.celsius; }
};
console.log(+right); // 21Returning a symbol, or forgetting a hint
A symbol is a primitive, so returning one is allowed. But the next step, converting it to a number or string implicitly, throws (see the earlier chapter on string conversion). Also, if your method handles only "number" and "string", it returns undefined for "default". Then obj + 1 gives NaN and obj + '' gives "undefined". Always end the method with a return that covers every remaining case.
Built-in Precedent: Date
Date.prototype[Symbol.toPrimitive] is the best-known built-in implementation. It treats "default" as "string". That is why adding to a date concatenates, while subtracting from it gives numbers:
const d = new Date(0);
console.log(typeof (d + 1)); // "string"
console.log(d - 0); // 0
console.log(d[Symbol.toPrimitive]('number')); // 0
console.log(typeof d[Symbol.toPrimitive]('default')); // "string"
try {
d[Symbol.toPrimitive]('bogus');
} catch (e) {
console.log(e instanceof TypeError); // true
}Date's method also rejects unknown hints. The engine only ever passes the three valid hints, so the check only matters when you call the method yourself. You can borrow this habit in your own classes if you call the method directly in tests.
When to Use It
| Situation | Recommendation |
|---|---|
| Value types where math is natural (money, durations, vectors' magnitude) | Good fit, with a documented `"default"` |
| You only need a nicer string form | Override `toString()` instead, it's simpler |
| Domain objects such as users or requests | Avoid it. Silent coercion hides bugs |
| You need to tell `+` apart from unary `+` | Only `Symbol.toPrimitive` can do this |
Coercion runs implicitly, so a bug in this method appears far from where the method is defined. Keep it pure: no side effects, no I/O, and the same result for the same hint.
Exercise
Given const t = { [Symbol.toPrimitive](h) { return h === 'string' ? 'T' : 5; } };, what do t + 1, ` ${t} + 1 , t > 4, and t == 'T'` evaluate to, and why?
Show answer
t + 1 is 6, because binary + sends "default" and the method returns 5. ` ${t} + 1 is "T1", because the template literal sends "string" and gives "T", which is then concatenated with 1. t > 4 is true, because relational comparison sends "number" and 5 > 4. t == 'T'` is false, because == sends "default", which gives 5, and 5 == 'T' compares 5 with NaN.
Exercise
An object defines valueOf() { return 3; } and [Symbol.toPrimitive]() { return {}; }. What happens with obj * 2, and how would you fix the method so that multiplication gives 6?
Show answer
It throws a TypeError. When Symbol.toPrimitive exists, its result must be a primitive, and the engine never falls back to valueOf. One fix is to return this.valueOf() from the method. Another is to delete the Symbol.toPrimitive property, or set it to undefined, so the fallback calls valueOf and multiplication gives 6.
Exercise
Write a Duration class holding ms whose instances give milliseconds in arithmetic and comparisons, and a string like "1.5s" in template literals.
Show answer
class Duration { constructor(ms) { this.ms = ms; } [Symbol.toPrimitive](hint) { return hint === 'string' ? ${this.ms / 1000}s : this.ms; } } Then new Duration(1500) + 500 is 2000, new Duration(1500) > 1000 is true, and ` ${new Duration(1500)} ` is "1.5s".