Emmanuel Akinfulubi

JavaScriptFundamental (ES6), part 2

Custom type conversion with Symbol.toPrimitive in JavaScript

65 Symbol.toPrimitive decides what your object becomes

hard

Give a money class a Symbol.toPrimitive that answers all three hints: 'number', 'string' and 'default'. Work out which hint each of Number(), a template literal, +, > and == asks for. Add toString and valueOf as well, and see which of the three wins.

Stuck? Three hints, smallest first
  1. 1. Three hints only. Arithmetic and comparison ask for number, String() and template literals ask for string, and binary + and == ask for default.
  2. 2. Symbol.toPrimitive is consulted before valueOf and toString, so those two become unreachable.
  3. 3. JSON.stringify does not convert to a primitive at all. It looks for toJSON.

The answer

class Naira {
  constructor(kobo) { this.kobo = kobo; }
  [Symbol.toPrimitive](hint) {
    if (hint === 'number') return this.kobo / 100;
    if (hint === 'string') return '\u20a6' + (this.kobo / 100).toFixed(2);
    return 'Naira(' + this.kobo + ' kobo)';            // 'default'
  }
  toString() { return 'toString ran'; }
  valueOf() { return -1; }
  toJSON() { return { naira: this.kobo / 100 }; }
}

const fare = new Naira(45000);       // 450 naira
const tip = new Naira(5000);         // 50 naira

const asNumber = [Number(fare), +fare];
const arithmetic = [fare * 2, fare - tip, Math.max(fare, tip)];
const asString = [String(fare), `fare is ${fare}`, fare.toFixed ? 'has toFixed' : 'no toFixed'];
const concatenated = fare + '';
const added = fare + tip;
const compared = [fare > tip, [fare, tip].sort((a, b) => a - b).map((m) => m.kobo)];
const looseEqual = fare == 'Naira(45000 kobo)';
const serialised = JSON.stringify({ fare });
const unreachable = [String(fare) === 'toString ran', Number(fare) === -1];

console.log('number hint :', asNumber, arithmetic);
console.log('string hint :', asString.slice(0, 2));
console.log('default hint:', concatenated, '|', added);
console.log('serialised  :', serialised);

Output


      
8 checks that prove this answer

You do not have to read these. They are part of the answer panel above, so pressing Run there executes all 8 of them and prints ok for each. That output is the proof, and the build fails if a single check fails.

8 checks

test('Number() and unary + ask for the number hint', asNumber, [450, 450]);
test('so does every arithmetic operator and Math function', arithmetic, [900, 400, 450]);
test('String() and a template literal ask for the string hint', asString.slice(0, 2), ['\u20a6450.00', 'fare is \u20a6450.00']);
test('binary + and == ask for default, which is neither of those', [concatenated, added, looseEqual], ['Naira(45000 kobo)', 'Naira(45000 kobo)Naira(5000 kobo)', true]);
test('comparison uses the number hint, so sorting works with no accessor', compared, [true, [5000, 45000]]);
test('toString and valueOf are now unreachable: toPrimitive is asked first', unreachable, [false, false]);
test('JSON.stringify ignores all of it and uses toJSON', serialised, '{"fare":{"naira":450}}');
test('and the object is still an object, with its own data intact', [fare.kobo, typeof fare], [45000, 'object']);

+ between two objects is the one that catches people. It does not ask for a string and it does not ask for a number — it asks for 'default', because at that point the language does not yet know whether it is doing addition or concatenation. Return a number from the default branch and fare + tip is 500; return a string and it concatenates. The fourth assertion is the same hint reached three ways: obj + '', obj + obj and obj == 'text'.

Comparison is different: <, >, -, * and Math.max all ask for 'number', which is what makes the fifth assertion work — a subtraction comparator sorts these objects without touching .kobo. And a template literal always asks for 'string', which is why `${obj}` and obj + '' can produce different text from the same object.

The sixth assertion is the trap. Adding Symbol.toPrimitive to a class that already had toString and valueOf silently retires both of them: OrdinaryToPrimitive is only reached when Symbol.toPrimitive is absent. That is a fine way to break code elsewhere that relied on the old toString, so if you add one, make the string branch return what toString used to.

JSON.stringify is not part of this protocol at all. It never coerces to a primitive; it looks for toJSON and otherwise walks the own enumerable properties. So an object can print as ₦450.00, add as text and serialise as {"naira":450} — three representations, three separate hooks, and no way to unify them.

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.