Course contentsShow
← JavaScript
Lesson 281 of 2,7238. Type CoercionFree lesson

ToPrimitive and Symbol.toPrimitive

How objects are converted to primitives and customizing conversion with Symbol.toPrimitive.

ToPrimitive and Symbol.toPrimitive

You'll learn how JavaScript decides which primitive value to use when converting objects, and how to customize that conversion.

What is ToPrimitive?

When JavaScript needs to convert an object to a primitive value (like in arithmetic operations or string concatenation), it uses an internal algorithm called ToPrimitive. This algorithm tries to call special methods on the object in a specific order to get a primitive result.

By default, ToPrimitive looks for two methods on objects:

  • valueOf() - typically returns a numeric representation
  • toString() - returns a string representation

The order it tries them depends on the hint: if JavaScript needs a number, it tries valueOf() first. If it needs a string, it tries toString() first.

Customizing with Symbol.toPrimitive

You can take complete control of this conversion by defining a Symbol.toPrimitive method on your object. This method receives a hint ("number", "string", or "default") and returns the primitive value you want.

const myObj = {
  value: 42,
  [Symbol.toPrimitive](hint) {
    if (hint === "number") {
      return this.value;
    }
    if (hint === "string") {
      return `Value: ${this.value}`;
    }
    return this.value; // default hint
  }
};

console.log(+myObj);        // 42 (hint: "number")
console.log(`${myObj}`);    // "Value: 42" (hint: "string")
console.log(myObj + 10);    // 52 (hint: "default", treated as number)

When Symbol.toPrimitive is defined, JavaScript skips the valueOf()/toString() dance entirely and uses your custom method instead.

Key Takeaway: JavaScript converts objects to primitives using the ToPrimitive algorithm, which you can fully customize by implementing Symbol.toPrimitive to control exactly what primitive value your object produces in different contexts.