Sub topic 3
Controlling Coercion, Tags, and Privacy with Symbols
This chapter assumes you know ES6 classes, computed property names, and the symbol basics from the earlier chapters. It covers the well-known symbols that shape conversion and type checks, then shows where symbols stop being useful as a way to hide data.
Symbol.toPrimitive
When JavaScript needs a primitive from an object, it first looks for a Symbol.toPrimitive method. The method receives a hint: 'number', 'string', or 'default'. The + operator and == pass 'default'.
const temperature = {
celsius: 21,
[Symbol.toPrimitive](hint) {
if (hint === 'string') return `${this.celsius} C`;
return this.celsius;
}
};
console.log(+temperature); // 21
console.log(`${temperature}`); // "21 C"
console.log(temperature + 1); // 22If the method returns an object, JavaScript throws a TypeError.
Symbol.toStringTag and Symbol.hasInstance
Symbol.toStringTag sets the tag that Object.prototype.toString reports. A static Symbol.hasInstance method replaces the prototype-chain check that instanceof normally performs.
class Queue {
get [Symbol.toStringTag]() { return 'Queue'; }
}
class Even {
static [Symbol.hasInstance](v) {
return Number.isInteger(v) && v % 2 === 0;
}
}
console.log(Object.prototype.toString.call(new Queue())); // "[object Queue]"
console.log(4 instanceof Even); // trueSymbols Are Not Private
Any code that holds the object can call Object.getOwnPropertySymbols or Reflect.ownKeys and read symbol keys. If you need real privacy, use one of the other options below.
| Technique | Hidden from outside code? | Notes |
|---|---|---|
| Symbol key | No | Skipped by `Object.keys` and JSON, but found by reflection |
| `#private` field | Yes | Only reachable inside the class body |
| WeakMap keyed by object | Yes, if the map stays private | Entries are garbage-collected along with the key |
Symbols as WeakMap Keys
Since ES2023, non-registered symbols can be WeakMap keys. Registered symbols from Symbol.for never get garbage-collected, so using one as a key throws.
const meta = new WeakMap();
const token = Symbol('token');
meta.set(token, { issued: 1 });
console.log(meta.get(token)); // { issued: 1 }
try {
meta.set(Symbol.for('shared'), 1);
} catch (e) {
console.log(e instanceof TypeError); // true
}Practical Patterns and Pitfalls
- Use symbol keys for metadata that must not collide with user-defined property names.
- Use
Symbol.forwith namespaced keys such as'app.theme'when separate modules must share one symbol. - Wrap symbols in
String()before you log or concatenate them, because implicit conversion throws. - Don't treat symbol keys as security. Use private fields instead.
Exercise
An object's Symbol.toPrimitive method returns this.value for every hint. What does ${obj} produce when value is 5, and why?
Show answer
It produces "5". The template literal passes the 'string' hint, the method returns the number 5, and the template literal then converts that number to a string.
Exercise
You need per-instance data that no outside code can read, even through reflection. Should you use a symbol key? What should you use instead?
Show answer
No. Reflect.ownKeys exposes symbol keys. Use a #private class field, or a WeakMap that is kept in module scope and keyed by the instance.