JavaScriptFundamental (ES6), part 1
Symbol.toPrimitive and Symbol.toStringTag in JavaScript
133 Symbol.toPrimitive and Symbol.toStringTag
hardWrite a Money class with a private kobo field and a Symbol.toPrimitive that answers all three hints differently: a number for arithmetic, a formatted naira string for text, and something else again for the default. Add Symbol.toStringTag. Then work out which operator asks for which hint — + and - do not agree — and see what JSON.stringify makes of a private field.
Stuck? Three hints, smallest first
- 1.
[Symbol.toPrimitive](hint)is called with'number','string'or'default'. Handle all three or one path returns undefined. - 2. Only
+,==and template-free coercion use the default hint.-,*,>and unary+all ask for a number. - 3.
Symbol.toStringTagchangesObject.prototype.toString, nothing else — and it is ignored entirely whenSymbol.toPrimitiveexists.
class Money {
#kobo;
constructor(kobo) { this.#kobo = kobo; }
get kobo() { return this.#kobo; }
get [Symbol.toStringTag]() { return 'Money'; }
[Symbol.toPrimitive](hint) {
if (hint === 'number') return this.#kobo;
if (hint === 'string') return `₦${(this.#kobo / 100).toFixed(2)}`;
return `Money(${this.#kobo})`;
}
}
class Tagged {
get [Symbol.toStringTag]() { return 'Tagged'; }
}
class Bare {
#hidden = 'invisible';
constructor() { this.shown = 1; }
}
const fare = new Money(50000);
const tip = new Money(32000);
const asNumber = +fare;
const inText = `the fare is ${fare}`;
const plussed = fare + 0;
const minussed = fare - 0;
const difference = fare - tip;
const bigger = fare > tip;
const tagOf = Object.prototype.toString.call(fare);
const tagOfTagged = Object.prototype.toString.call(new Tagged());
const taggedInText = `${new Tagged()}`;
console.log('hints :', asNumber, '|', inText, '|', plussed);
console.log('maths :', minussed, difference, bigger);
console.log('tags :', tagOf, tagOfTagged, taggedInText);
Output
9 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 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('unary plus asks for a number', asNumber, 50000);
test('a template literal asks for a string', inText, 'the fare is ₦500.00');
test('plus asks for the default hint, so this concatenated instead of adding', plussed, 'Money(50000)0');
test('minus asks for a number, so the very same object subtracts fine', [minussed, difference], [50000, 18000]);
test('comparison asks for a number too', bigger, true);
test('String and interpolation agree, both being the string hint', inText.endsWith(String(fare)), true);
test('toStringTag only changes this one thing', [tagOf, tagOfTagged], ['[object Money]', '[object Tagged]']);
test('with no toPrimitive, interpolation falls back to that same tag', taggedInText, '[object Tagged]');
test('a private field is invisible to stringify; only a normal one survives', JSON.stringify(new Bare()), '{"shown":1}');
Symbol.toPrimitive is the single hook for every implicit conversion, and it takes precedence over both valueOf and toString. Three hints, and the useful ones are unambiguous: 'number' for arithmetic and comparison, 'string' for interpolation and String(). The default hint is the awkward one, used by +, == and little else, and it exists because + cannot know whether you meant addition or concatenation.
Which is the trap the middle assertions catch. fare + 0 and fare - 0 ask for different hints, so a class where the default returns a string will concatenate under + and subtract correctly under -. If your object is fundamentally a number, return the number for the default too and the surprise disappears. Date goes the other way and returns a string for the default, which is exactly why date1 - date2 is a duration in milliseconds while date1 + date2 is nonsense.
Symbol.toStringTag is much smaller than it looks: it changes Object.prototype.toString, which shows up in debugging output and in old type-sniffing code, and nothing else. Once Symbol.toPrimitive exists it is not consulted for coercion at all — the second-to-last assertion is the only case where it reaches interpolation, and that is because Tagged has no toPrimitive to override it.