Symbol.for Shares Symbols Via A Registry
Share one symbol across modules through the Symbol.for registry, so hidden metadata keys match even when modules load separately.
Code
// Symbol() mints a brand-new symbol on every call
const local = Symbol('rate-limiter');
// Symbol.for('key') consults a process-wide registry: every module
// asking for the same key shares one symbol, so cross-module
// metadata lands on the same property
const shared = Symbol.for('rate-limiter');
const again = Symbol.for('rate-limiter');
console.log(shared === again);
console.log(local === shared);
// keyFor reads the registry key back; non-registry symbols have none
console.log(Symbol.keyFor(shared));
console.log(Symbol.keyFor(local));
// Practical shape: hidden metadata keyed by a shared registry symbol
const requestMeta = Symbol.for('app.requestMeta');
const request = { url: '/orders' };
request[requestMeta] = { retriedAt: 3 };
console.log(request[requestMeta].retriedAt);Output
Captured from a sandboxed run of this snippet in the build pipeline.
true
false
rate-limiter
undefined
3Registry symbol versus fresh symbol
Symbol('rate-limiter') mints local, a symbol no other call can reproduce, while Symbol.for('rate-limiter') looks the key up in a process-wide registry — so shared and again are the same symbol. The demo logs that difference directly: shared === again prints true, and local === shared prints false.
Reading the key back
Symbol.keyFor(shared) returns 'rate-limiter' because the symbol came from the registry; Symbol.keyFor(local) returns undefined because registry membership — not the description string — is what keyFor reports. The run’s five lines:
true
false
rate-limiter
undefined
3
The last line is the practical payoff: with requestMeta = Symbol.for('app.requestMeta'), request[requestMeta] stores { retriedAt: 3 } under a key no string property can collide with, and request[requestMeta].retriedAt reads 3 back.
The lines that share the identity
const shared = Symbol.for('rate-limiter');
const again = Symbol.for('rate-limiter');
Two modules running these same lines get one object identity — that shared identity is what makes cross-module metadata land on the same property.
Interactive Tools for This Topic
FAQ
- Are there third-party dependencies?
- No. The dependency list is empty; the code stays inside the standard library. Its state lives in module-level bindings: `local`, `shared`, `again`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.