Course contentsShow
← JavaScript
Lesson 1015 of 2,72323. SymbolsFree lesson

Symbol.toPrimitive for Type Coercion

Define custom conversion logic when objects are coerced to primitives using Symbol.toPrimitive.

Symbol.toPrimitive for Type Coercion

You'll learn how to control what happens when JavaScript tries to convert your object into a primitive value.

What Is Symbol.toPrimitive?

When JavaScript needs to convert an object to a primitive (like a number, string, or boolean), it normally uses default rules. But with Symbol.toPrimitive, you can define your own custom logic for these conversions.

Think of it like a translator: when someone asks "What's this object as a number?" or "as a string?", your custom method gets to answer.

How It Works

You define a method on your object using Symbol.toPrimitive as the key. This method receives a hint parameter telling you what type JavaScript is looking for:

  • "number" — JavaScript wants a numeric value
  • "string" — JavaScript wants a string
  • "default" — Could be either (like with + or ==)
const temperature = {
  celsius: 25,
  [Symbol.toPrimitive](hint) {
    if (hint === 'number') {
      return this.celsius;
    }
    if (hint === 'string') {
      return `${this.celsius}°C`;
    }
    return this.celsius; // default
  }
};

console.log(+temperature);        // 25 (number conversion)
console.log(`Temp: ${temperature}`); // "Temp: 25°C" (string conversion)
console.log(temperature + 10);    // 35 (default → number)

Why Use It?

Without Symbol.toPrimitive, JavaScript uses valueOf() and toString() with sometimes unpredictable results. This symbol gives you complete, explicit control over coercion behavior in one place.

Key Takeaway: Symbol.toPrimitive lets you define custom conversion logic by handling the "number", "string", and "default" hints, giving you precise control over how your object behaves in coercion contexts.