Skip to content
Tutorials Center
My learning

Topics

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.

JavaScript
const temperature = {
  celsius: 21,
  [Symbol.toPrimitive](hint) {
    return hint === "string" ? `${this.celsius} ยฐC` : this.celsius;
  },
};

Try it

JS What hint does each operation send?

Press Run (or Ctrl + Enter) to see the console output here.

No output.

JS A Money class

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Syntax

JavaScript
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}` and String(x) send "string". +x, Number(x), x * 2 and x > y send "number". x + 1 and x == 7 send "default".
  • The "default" case is the tricky one. Most objects treat it like "number", but built-in dates treat it as "string", which is why new Date() + 1 concatenates text.
  • It wins over valueOf() and toString(). 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() and valueOf() is enough, but Symbol.toPrimitive is 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.