Symbol.toPrimitive
The Symbol.toPrimitive
well-known symbol specifies a method that accepts a preferred type and returns a primitive representation of an object. It is called in priority by all type coercion algorithms.
Value
The well-known symbol Symbol.toPrimitive
.
Description
With the help of the Symbol.toPrimitive
property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument hint
, which specifies the preferred type of the result primitive value. The hint
argument can be one of "number"
, "string"
, and "default"
.
The "number"
hint is used by numeric coercion algorithms. The "string"
hint is used by the string coercion algorithm. The "default"
hint is used by the primitive coercion algorithm. The hint
only acts as a weak signal of preference, and the implementation is free to ignore it (as Symbol.prototype[Symbol.toPrimitive]()
does). The language does not enforce alignment between the hint
and the result type, although [Symbol.toPrimitive]()
must return a primitive, or a TypeError
is thrown.
Objects without the Symbol.toPrimitive
property are converted to primitives by calling the valueOf()
and toString()
methods in different orders, which is explained in more detail in the type coercion section. Symbol.toPrimitive
allows full control over the primitive conversion process. For example, Symbol.prototype.toString()
won't be called, and Symbol
objects must always be explicitly converted to strings through String()
.