Customize conversion with Symbol.toPrimitive
Quick answer
An object can define a method at Symbol.toPrimitive to control its conversion into a primitive. This method receives a hint about the requesting operation.
How it works
[Symbol.toPrimitive](hint) receives "number", "string" or "default". Return a primitive; returning an object throws TypeError. If the hook is absent, ordinary conversion tries valueOf and toString in an order determined by the hint (Date has special behavior). Addition first requests primitive conversion with the default hint, then chooses concatenation or arithmetic. Boolean conversion of an ordinary object does not invoke this hook.
const x={ [Symbol.toPrimitive](h){return h==="string"?"5 m":5;} }; console.log(String(x), Number(x), x+2);Expected output in Node.js:
5 m 5 7String uses the string hint, Number uses number and + uses default.
const x={ [Symbol.toPrimitive](){return 0;} }; console.log(Boolean(x), x==0);Expected output in Node.js:
true trueThe object is truthy even though primitive conversion yields zero.
Common mistakes
Do not return a boxed Number or assume the number hint means the hook must return a Number. Keep conversion side effects minimal.
Practice
Create a distance object whose numeric conversion returns meters and string conversion returns a unit label. Trace all three hints.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Customize conversion with Symbol.toPrimitive — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which hint does unary numeric conversion normally request?
What is required of a Symbol.toPrimitive result?
Does Boolean({[Symbol.toPrimitive](){return false;}}) call the hook?
What is the exact console output in Customize conversion with Symbol.toPrimitive example 1?
const x={ [Symbol.toPrimitive](h){return h==="string"?"5 m":5;} }; console.log(String(x), Number(x), x+2);What is the exact console output in Customize conversion with Symbol.toPrimitive example 2?
const x={ [Symbol.toPrimitive](){return 0;} }; console.log(Boolean(x), x==0);