CKTIS / JavaScript
Symbol.toPrimitive — custom object-to-primitive conversion
Symbol.toPrimitive is a well-known symbol identifying an object's primitive-conversion method. The method receives the hint "string", "number", or "default" and takes precedence over the ordinary use of valueOf() and toString().
Version: ECMAScript and Web APIs; exact feature edition and browser support reviewed per entry; Node 24 in repository does not prove browser API support
Syntax
const value = { [Symbol.toPrimitive](hint) { return hint === "string" ? "label" : 10; } };Symbol.toPrimitive is a symbol used as a method key, not a conversion function. Define [Symbol.toPrimitive](hint) { ... } to control an object's conversion to a primitive value. The method is called with the object being converted as this.
The hint argument is "string" for String(obj), "number" for Number(obj), and "default" for addition in obj + 3. The hint does not enforce the result type: the method must return a primitive, and the surrounding operation may convert it further. Returning an object throws TypeError, without trying valueOf() or toString().
If the property is undefined or null, ordinary conversion applies: a string hint tries toString() before valueOf(); a number hint reverses that order. With no hint, ordinary conversion uses the number preference. Any other non-callable property value throws TypeError.
In the example, String(amount) produces Amount(7), Number(amount) produces 7, and amount + 3 produces 10. Handle all three hints deliberately to avoid surprising results with the + operator.
Examples
const amount = {
value: 7,
[Symbol.toPrimitive](hint) {
if (hint === "string") return `Amount(${this.value})`;
return this.value;
}
};
console.log(String(amount));
console.log(Number(amount));
console.log(amount + 3);Result
Amount(7) 7 10
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.