JavaScript Reference ยท Iterators, Generators and Symbols
Symbol.toPrimitive
Reference for Symbol.toPrimitive: control how an object converts to a string, number or default primitive, with the hint argument explained by examples.
When JavaScript needs a primitive from an object (to concatenate it, compare it, do arithmetic or use it as a key), it runs an internal step called ToPrimitive. If the object has a method under the key Symbol.toPrimitive, that method is called and decides the result. Without it, the engine falls back to valueOf() and toString().
The method receives a hint string telling it what kind of value the caller prefers: "number", "string" or "default". One method can therefore return a number in arithmetic and a readable label in a template literal.
const temperature = { celsius: 21, [Symbol.toPrimitive](hint) { return hint === "string" ? `${this.celsius} ยฐC` : this.celsius; }, };
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
obj[Symbol.toPrimitive](hint)
| Name | Description |
|---|---|
hint |
"string" when a string is expected (template literals, String(), property keys), "number" when a number is expected (unary +, Number(), -, *, /, relational comparison), and "default" for operators that cannot tell (binary +, ==). |
Return value: a primitive value (string, number, boolean, null, undefined, symbol or bigint). It does not have to match the hint.
Exceptions: a TypeError if the method returns an object, or if Symbol.toPrimitive exists but is not a function (and is not null or undefined).
Usage notes
- Hint-by-operation:
`${x}`andString(x)send"string".+x,Number(x),x * 2andx > ysend"number".x + 1andx == 7send"default". - The
"default"case is the tricky one. Most objects treat it like"number", but built-in dates treat it as"string", which is whynew Date() + 1concatenates text. - It wins over
valueOf()andtoString(). When the method exists, those two are not consulted at all. - Only a primitive result is accepted. Returning an object throws; the engine does not retry with
valueOf(). - Alternatives. For simple classes, defining
toString()andvalueOf()is enough, butSymbol.toPrimitiveis clearer because the hint is explicit. - Do not overuse it. Objects that silently behave like numbers can surprise readers; keep it for value-like types such as money, units or durations.
Browser support
Symbol.toPrimitive works in every current browser and in Node.js.