Symbol.toPrimitive Steers Object Coercion
Object-to-primitive conversion asks Symbol.toPrimitive first, then valueOf or toString depending on the hint, so numeric and string contexts can disagree.
Code
// object-to-primitive conversion consults Symbol.toPrimitive first: the hint is 'string' | 'number' | 'default'
const money = {
cents: 1250,
[Symbol.toPrimitive](hint) {
console.log('hint:', hint);
return hint === 'string' ? '¥' + this.cents / 100 : this.cents;
},
};
console.log('String(money) :', String(money)); // hint string
console.log('unary plus :', +money); // hint number
console.log('template :', `${money}`); // template literals run ToString: hint string
console.log('money + 50 :', money + 50); // arithmetic uses default
// without Symbol.toPrimitive the hint picks valueOf or toString:
// the + operator uses default and tries valueOf first; template literals and String() use string and try toString first
const plain = {
valueOf() {
return 7;
},
toString() {
return 'seven';
},
};
console.log('plain template:', `${plain}`);
console.log('plain + 1 :', plain + 1);
console.log('String(plain) :', String(plain));What the code does
Top-level bindings money, plain hold the demo state — nothing sits inside a function scope.
Using it
The run emits 8 labeled sections — hint:, String(money) :, unary plus :, template :, money + 50 :, plain template:, plain + 1 :, String(plain) : — one per step.
Key statements
return hint === 'string' ? '¥' + this.cents / 100 : this.cents;
return 'seven';
Interactive Tools for This Topic
FAQ
- What has to be installed first?
- Nothing — the runtime itself provides everything the code touches. Its state lives in module-level bindings: `money`, `plain`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.