Sub topic 14
Practical Patterns and Common Pitfalls
This chapter pulls together everything from the earlier chapters and applies it to real code. It assumes you already know how Symbol() and Symbol.for() differ, which operations skip symbol keys, how Symbol.iterator works, and why symbols do not give privacy. The focus here is on deciding when a symbol is the right tool and on the bugs that appear once symbols meet serialization, copying, and multiple copies of a library.
Pattern: Attaching Metadata to Objects You Do Not Own
Sometimes a library has to mark objects that belong to someone else. Examples include objects it has already processed, cached results, or framework bookkeeping. A string key such as _visited can clash with a property the owner already uses. A local symbol cannot clash, and ordinary enumeration skips it.
const visited = Symbol('visited');
function walk(node, visit) {
if (node === null || typeof node !== 'object' || node[visited]) return;
node[visited] = true;
visit(node);
for (const child of Object.values(node)) walk(child, visit);
}
const a = { name: 'a' };
const b = { name: 'b', ref: a };
a.ref = b; // cycle
walk(a, (n) => console.log(n.name)); // "a", then "b"
console.log(Object.keys(a)); // ['name', 'ref']
console.log(JSON.stringify({ x: 1, [visited]: true })); // {"x":1}This pattern changes the caller's objects, and it fails on frozen objects. In strict mode, assigning to a frozen object throws a TypeError. When you only need to know whether you have seen an object, a WeakSet usually works better because it never touches the object:
function walkClean(node, visit, seen = new WeakSet()) {
if (node === null || typeof node !== 'object' || seen.has(node)) return;
seen.add(node);
visit(node);
for (const child of Object.values(node)) walkClean(child, visit, seen);
}
const frozen = Object.freeze({ name: 'frozen' });
walkClean(frozen, (n) => console.log(n.name)); // "frozen"Use the symbol key when the metadata has to travel with the object to other code. Use the WeakSet or WeakMap when the bookkeeping only matters inside your own code.
Pattern: Brand Checks That Survive Duplicate Library Copies
Large applications often end up with two copies of the same package, for example two versions in node_modules or one copy per iframe. Each copy runs its own Symbol('...') call and its own class declaration. Because of that, local symbols and instanceof checks both fail across the copies. A registered symbol has the same identity everywhere in the runtime, so it still works.
function createLibrary() {
const localBrand = Symbol('mylib.Money');
const sharedBrand = Symbol.for('mylib.Money');
class Money {
constructor(amount) {
this.amount = amount;
this[localBrand] = true;
this[sharedBrand] = true;
}
}
return {
Money,
isMoneyLocal: (v) => v != null && v[localBrand] === true,
isMoneyShared: (v) => v != null && v[sharedBrand] === true,
};
}
const libA = createLibrary(); // first copy of the package
const libB = createLibrary(); // second copy of the package
const price = new libA.Money(5);
console.log(price instanceof libB.Money); // false
console.log(libB.isMoneyLocal(price)); // false
console.log(libB.isMoneyShared(price)); // trueReact uses this idea. It marks elements with Symbol.for('react.element'), so elements made by one copy of React are still recognized by another.
Pattern: Symbol Constants Instead of String Enums
Symbols make good enum values when the values only live in memory. A typo or a stray string cannot match by accident, because only the exact symbol is equal to itself.
const Status = Object.freeze({
IDLE: Symbol('idle'),
LOADING: Symbol('loading'),
DONE: Symbol('done'),
});
function label(status) {
switch (status) {
case Status.IDLE: return 'Idle';
case Status.LOADING: return 'Loading...';
case Status.DONE: return 'Done';
default: throw new TypeError(`Unknown status: ${String(status)}`);
}
}
console.log(label(Status.LOADING)); // "Loading..."
try {
label('loading');
} catch (e) {
console.log(e.message); // "Unknown status: loading"
}
console.log(JSON.stringify({ status: Status.DONE })); // {}
console.log(JSON.stringify([Status.DONE])); // [null]The last two lines show the cost. When a symbol is a property value, JSON.stringify drops the property silently. Inside an array it becomes null. structuredClone and postMessage throw a DataCloneError when they meet a symbol value. If the state has to go to a server, localStorage, or a worker, use strings. You can also convert with status.description on the way out and map the string back to the symbol on the way in.
Pitfall: Copying Objects Loses (or Keeps) Symbol Keys Unpredictably
Each copying tool treats symbol keys differently. Mistakes here cause subtle bugs where metadata vanishes after a copy.
const meta = Symbol('meta');
const hidden = Symbol('hidden');
const src = { name: 'report', [meta]: { version: 2 } };
Object.defineProperty(src, hidden, { value: 'x', enumerable: false });
const spread = { ...src };
const assigned = Object.assign({}, src);
const viaJson = JSON.parse(JSON.stringify(src));
const cloned = structuredClone(src);
console.log(spread[meta], spread[hidden]); // { version: 2 } undefined
console.log(assigned[meta], assigned[hidden]); // { version: 2 } undefined
console.log(viaJson[meta]); // undefined
console.log(cloned[meta]); // undefined| Operation | Enumerable symbol keys | Non-enumerable symbol keys |
|---|---|---|
| `{ ...obj }` | Copied | Skipped |
| `Object.assign` | Copied | Skipped |
| `JSON.stringify` | Dropped | Dropped |
| `structuredClone` | Dropped | Dropped |
| `Object.keys`, `Object.entries`, `for...in` | Skipped | Skipped |
| `Object.getOwnPropertyDescriptors` | Included | Included |
| `Reflect.ownKeys` | Included | Included |
A hand-written utility that loops over Object.keys has the same blind spot. A shallow-equality check written that way treats two objects as equal even when their symbol-keyed data differs. Use Reflect.ownKeys when the utility has to be complete:
const tag = Symbol('tag');
function shallowEqualKeys(a, b) {
const ka = Object.keys(a);
return ka.length === Object.keys(b).length && ka.every((k) => Object.is(a[k], b[k]));
}
function shallowEqualAll(a, b) {
const ka = Reflect.ownKeys(a);
return ka.length === Reflect.ownKeys(b).length && ka.every((k) => Object.is(a[k], b[k]));
}
const x = { n: 1, [tag]: 'red' };
const y = { n: 1, [tag]: 'blue' };
console.log(shallowEqualKeys(x, y)); // true (wrong)
console.log(shallowEqualAll(x, y)); // false (correct)To make an exact shallow copy that keeps every symbol key, the prototype, and getters, copy the descriptors:
function exactCopy(obj) {
return Object.create(
Object.getPrototypeOf(obj),
Object.getOwnPropertyDescriptors(obj)
);
}
const secret = Symbol('secret');
const original = {};
Object.defineProperty(original, secret, { value: 7, enumerable: false });
console.log(exactCopy(original)[secret]); // 7Pitfall: One-Shot Iterables
A common shortcut makes an object its own iterator by returning this from [Symbol.iterator](). That object can only be iterated once, because the position is stored on the object itself.
const oneShot = {
items: [1, 2],
index: 0,
[Symbol.iterator]() { return this; },
next() {
return this.index < this.items.length
? { value: this.items[this.index++], done: false }
: { value: undefined, done: true };
},
};
console.log([...oneShot]); // [1, 2]
console.log([...oneShot]); // []
const reusable = {
items: [1, 2],
*[Symbol.iterator]() { yield* this.items; },
};
console.log([...reusable]); // [1, 2]
console.log([...reusable]); // [1, 2]A collection should return a fresh iterator on every call, and a generator method does this for you. Returning this is correct only for objects that are iterators themselves, such as the objects generators return, and callers expect those to be used up.
Pitfall: Implicit String Conversion in Logs and Keys
Symbols throw a TypeError when converted implicitly. Error messages and log lines are where this shows up most, often inside a catch block that was meant to report a different error. Always convert explicitly:
const token = Symbol('session');
console.log(`key=${String(token)}`); // "key=Symbol(session)"
console.log(`key=${token.description}`); // "key=session"
try {
console.log(`key=${token}`);
} catch (e) {
console.log(e instanceof TypeError); // true
}console.log(token) on its own is safe because the console formats the value itself. The error only appears when JavaScript has to turn the symbol into a string: in template literals, with +, or when the symbol is passed to an API that expects a string.
Choosing the Right Tool
| Need | Best choice | Why |
|---|---|---|
| True privacy for class state | `#private` fields | No outside code can reach them, not even through reflection |
| Private data about objects you do not own | `WeakMap` | Leaves the object untouched and works on frozen objects |
| Collision-free extension key in one codebase | `Symbol()` | Unique, and skipped by `Object.keys` and JSON |
| Protocol shared across packages or realms | `Symbol.for('ns.name')` | Same identity everywhere |
| Data that must be serialized | String key | Symbols do not survive serialization |
| Hooking into language behavior | Well-known symbols | The only way to customize iteration, coercion, and tags |
Exercise
A utility library marks validated objects with obj[Symbol('validated')] = true and checks the mark later with isValidated(obj). Users report that objects validated in one bundle show up as unvalidated in another bundle on the same page. Explain the cause and give a fix.
Show answer
Each bundle includes its own copy of the library, so each copy runs its own Symbol('validated') call and gets a different symbol. A mark set by one copy is invisible to the other copy. Use a registered symbol with a namespaced key, Symbol.for('mylib.validated'), so that both copies get the same symbol. Another option is to keep validation state in one shared WeakSet, provided both bundles can reach that one instance.
Exercise
An object { id: 1, [Symbol('cache')]: data } is copied with { ...obj }, saved with JSON.stringify, and sent to a worker with postMessage. Which of these keep the cache property?
Show answer
Only the spread copy keeps it, because spread copies enumerable symbol-keyed properties. JSON.stringify drops symbol keys. postMessage uses the structured clone algorithm, which also ignores symbol keys, so the worker gets { id: 1 }.
Exercise
Why does [...collection] return an empty array the second time when collection[Symbol.iterator] is written as return this and next() is defined on the object? How do you fix it?
Show answer
The read position (index) is stored on the object, and nothing resets it. The second spread gets the same, already finished iterator. Make [Symbol.iterator] a generator method, such as *[Symbol.iterator]() { yield* this.items; }, so that every call returns a new iterator with its own position.