Sub topic 14
Practical Patterns and Common Pitfalls
This chapter assumes you already know how to create symbols, use them as property keys, read them back through reflection, and share them with Symbol.for. It shows where symbols work well in everyday code and where they tend to cause bugs.
Pattern: Attaching Metadata to Objects You Don't Own
Sometimes you need to attach information to an object that another part of the program also uses. A string key could clash with that code's properties or end up in its serialized output. A module-scoped symbol avoids both problems.
const kMeta = Symbol('meta');
function tag(obj, info) {
obj[kMeta] = info;
return obj;
}
const record = tag({ id: 1 }, { source: 'cache' });
console.log(record[kMeta].source); // "cache"
console.log(Object.keys(record)); // ['id']
console.log(JSON.stringify(record)); // {"id":1}Only code that can reach kMeta reads the metadata by name. Other code doesn't see it in for...in loops, Object.keys, or JSON output.
Pattern: Enum-Like Constants
Strings used as enum values can match by accident: any 'active' string equals any other. Symbols can only match themselves, so a value from somewhere else can never pass as one of your constants.
const Status = Object.freeze({
ACTIVE: Symbol('active'),
CLOSED: Symbol('closed'),
});
function label(status) {
switch (status) {
case Status.ACTIVE: return 'Active';
case Status.CLOSED: return 'Closed';
default: throw new TypeError(`Unknown status: ${String(status)}`);
}
}
console.log(label(Status.ACTIVE)); // "Active"
// label('active'); // TypeError: Unknown status: activeThere is a trade-off. Symbols can't be serialized, so these constants can't go into JSON, localStorage, or a network request without a separate mapping to strings.
Choosing the Right Tool
When you use Symbol.for, prefix the key with a namespace such as 'mylib.cache'. Every piece of code in the runtime shares the registry, so a short key like 'cache' can collide with someone else's.
Common Pitfalls
Implicit String Conversion
Template literals and + concatenation both throw a TypeError when they meet a symbol. This often shows up in error messages and log lines, which is why the label function above wraps the value in String(status).
const s = Symbol('debug');
console.log(String(s)); // "Symbol(debug)"
console.log(s.description); // "debug"
// console.log(`${s}`); // TypeErrorSpread and Object.assign Copy Symbol Keys
Symbol keys stay out of Object.keys, but object spread and Object.assign still copy enumerable symbol-keyed properties. Your metadata can therefore travel to copies you didn't expect.
const kMeta = Symbol('meta');
const original = { id: 1, [kMeta]: 'internal' };
const copy = { ...original };
console.log(copy[kMeta]); // "internal"To keep a symbol property from being copied, define it with Object.defineProperty, which makes it non-enumerable by default.
Duplicate Library Copies
If a bundle contains two copies of a library and each copy calls Symbol('brand'), each copy creates its own symbol. A brand check from one copy then rejects objects from the other. Use Symbol.for when the identity check has to work across package copies or realms.
Registered Symbols Can't Be Weak Keys
A WeakMap accepts only non-registered symbols as keys. Registered symbols live for the whole lifetime of the runtime, so the engine can never garbage-collect them.
const wm = new WeakMap();
wm.set(Symbol('ok'), 1); // works
// wm.set(Symbol.for('nope'), 1); // TypeError| Pitfall | Symptom | Fix |
|---|---|---|
| Template literal with a symbol | TypeError at runtime | Use `String(sym)` or `sym.description` |
| Spreading objects with symbol keys | Hidden data appears on copies | Make the property non-enumerable |
| Expecting symbol keys to be private | Other code reads them through `Object.getOwnPropertySymbols` | Use `#private` fields or a WeakMap |
| Duplicate package copies | Brand checks fail | Use a namespaced `Symbol.for` key |
| Short registry keys | Collisions with other code | Prefix keys, for example `'mylib.x'` |
Exercise
A logging helper runs console.log(Status: ${order.status}), where order.status holds Status.CLOSED from the enum above. What happens, and how would you fix it?
Show answer
The template literal tries to convert the symbol to a string implicitly, so it throws a TypeError. Convert it explicitly instead, for example ${String(order.status)} (which prints "Symbol(closed)") or ${order.status.description} (which prints "closed").
Exercise
Two independently installed copies of a plugin library need to recognize each other's objects through a brand property. Should the brand key be Symbol('brand') or Symbol.for('plugin.brand'), and why?
Show answer
Use Symbol.for('plugin.brand'). Each Symbol() call creates a separate symbol, so the two copies would never match. The global registry returns the same symbol for the same key everywhere in the runtime, and the namespace prefix lowers the chance of clashing with other code.