Sub topic 5
Sharing Symbols with the Global Registry
Earlier chapters showed that every call to Symbol() creates a value that is never equal to any other symbol. That uniqueness prevents name collisions. It also causes a problem when two separate pieces of code need to agree on the same symbol and cannot import it from a shared place. The global symbol registry solves this. It is a runtime-wide table that maps string keys to symbols, accessed through Symbol.for and Symbol.keyFor.
This chapter assumes you know JavaScript primitive types and typeof, computed property names, ES modules or CommonJS, and the symbol basics covered in the earlier chapters (uniqueness, descriptions, and symbol-keyed properties).
The Problem: Uniqueness Across Boundaries
Inside a single module, sharing a symbol is easy. You create it once and export it:
// brand.js
export const BRAND = Symbol('mylib.brand');
// consumer.js
import { BRAND } from './brand.js';
const obj = { [BRAND]: true };This only works if every consumer imports the same module instance. In real projects that assumption breaks in several ways:
- Duplicate package copies. A bundler or
node_modulestree may contain two versions of the same library. Each copy runs its ownSymbol('mylib.brand'), so you end up with two different symbols. Objects branded by one copy fail the check in the other. - Multiple realms. A realm is a separate global environment with its own set of built-ins. An iframe, a Node
vmcontext, and a ShadowRealm each have their ownObject,Array, andSymbol. A module loaded in each realm creates its own local symbols. - No shared import path. Two independent libraries may want to cooperate on a protocol without either depending on the other.
In each case you need a symbol that both sides can obtain from a name alone.
Symbol.for: Look Up or Create
Symbol.for(key) searches the global registry for an entry with the given string key. If it finds one, it returns that symbol. If not, it creates a new symbol, stores it under the key, and returns it.
const s1 = Symbol.for('app.theme');
const s2 = Symbol.for('app.theme');
console.log(s1 === s2); // true
console.log(s1.description); // "app.theme"
console.log(typeof s1); // "symbol"
const local = Symbol('app.theme');
console.log(local === s1); // falseThe registered symbol is a normal symbol in every other way. You can use it as a property key, it is skipped by Object.keys and JSON.stringify, and it shows up in Object.getOwnPropertySymbols. The only difference is that its identity comes from a string, so any code that knows the string can get it.
Note the last comparison. Symbol('app.theme') and Symbol.for('app.theme') are different values. The description is just a label. Symbol() never consults the registry.
Key Conversion
The key is always converted to a string first. This has some consequences you might not expect:
console.log(Symbol.for(1) === Symbol.for('1')); // true
console.log(Symbol.for() === Symbol.for('undefined')); // true
console.log(Symbol.for(null) === Symbol.for('null')); // true
console.log(Symbol.for({}) === Symbol.for('[object Object]')); // trueCalling Symbol.for() with no argument does not create an anonymous symbol. It registers the key "undefined". Passing an object almost always registers "[object Object]", which collides with every other object you pass. Always pass an explicit, deliberate string.
Symbol.keyFor: Reverse Lookup
Symbol.keyFor(sym) returns the registry key for a registered symbol, or undefined if the symbol is not in the registry.
const registered = Symbol.for('app.theme');
const local = Symbol('app.theme');
console.log(Symbol.keyFor(registered)); // "app.theme"
console.log(Symbol.keyFor(local)); // undefined
console.log(Symbol.keyFor(Symbol.iterator)); // undefined
try {
Symbol.keyFor('app.theme');
} catch (e) {
console.log(e instanceof TypeError); // true
}Three points stand out:
keyForis the only reliable way to tell whether a symbol is registered. Thedescriptionproperty cannot tell you, because a local symbol can have exactly the same description.- Well-known symbols such as
Symbol.iteratorare shared across realms, but they are not stored in the registry.keyForreturnsundefinedfor them. - Passing a non-symbol throws a
TypeErrorinstead of returningundefined.
A small helper makes the check explicit:
function isRegisteredSymbol(value) {
return typeof value === 'symbol' && Symbol.keyFor(value) !== undefined;
}
console.log(isRegisteredSymbol(Symbol.for('a'))); // true
console.log(isRegisteredSymbol(Symbol('a'))); // false
console.log(isRegisteredSymbol('a')); // falseCrossing Realms
The specification says the registry is shared by all realms in the same agent, meaning the same thread of execution. A symbol registered in an iframe is the same symbol in the parent page. You can see this in Node with the built-in vm module, which runs code in a fresh realm:
const vm = require('node:vm');
const fromOtherRealm = vm.runInNewContext("Symbol.for('app.theme')");
console.log(fromOtherRealm === Symbol.for('app.theme')); // true
const localOther = vm.runInNewContext("Symbol('app.theme')");
console.log(localOther === Symbol('app.theme')); // false
const otherIterator = vm.runInNewContext('Symbol.iterator');
console.log(otherIterator === Symbol.iterator); // trueThe new context has its own Symbol function, but Symbol.for reaches the shared registry. Well-known symbols are also identical across realms, which is why an array from an iframe can still be iterated by the parent page.
Registered vs. Local Symbols
| Property | `Symbol(desc)` | `Symbol.for(key)` |
|---|---|---|
| Identity | New value on every call | One value per key, runtime-wide |
| Equal to another symbol with same text | Never | Yes, if both registered |
| Same across realms | No | Yes (same agent) |
| `Symbol.keyFor` result | `undefined` | The key string |
| Can be obtained by unrelated code | Only if handed a reference | By anyone who knows the key |
| Usable as a WeakMap key | Yes | No |
| Garbage collected | Yes, when unreachable | Effectively lives for the whole runtime |
The last two rows are linked. A registered symbol can always be recreated from its key, so the engine cannot treat it as unreachable. For that reason registered symbols are rejected as WeakMap keys. A later chapter covers weak keys in detail.
Real-World Uses
The registry is common in libraries that must work even when several copies are loaded:
- React marks its elements with
Symbol.for('react.element')(andSymbol.for('react.transitional.element')in newer versions). Two copies of React on a page can still recognize each other's elements. - Node.js exposes
util.inspect.custom, which isSymbol.for('nodejs.util.inspect.custom'). A library can define a custom console representation without importingutil, so the same code also runs in browsers:
const inspect = Symbol.for('nodejs.util.inspect.custom');
class Money {
constructor(cents) {
this.cents = cents;
}
[inspect]() {
return `Money(${(this.cents / 100).toFixed(2)})`;
}
}
console.log(new Money(1999)); // In Node: Money(19.99)In a browser that property is simply ignored, and nothing breaks.
A brand check that survives duplicate package copies follows the same pattern:
const BRAND = Symbol.for('com.example.mylib.Collection');
class Collection {
constructor() {
this[BRAND] = true;
}
static isCollection(value) {
return value != null && value[BRAND] === true;
}
}
console.log(Collection.isCollection(new Collection())); // true
console.log(Collection.isCollection({})); // falseUnlike instanceof, this check works when the object came from another copy of the library or another realm.
Pitfalls
The Registry Is a Global String Namespace
Registered symbols bring back the collision risk that symbols were meant to remove. If two unrelated libraries both call Symbol.for('id'), they share one symbol and can overwrite each other's properties. Namespace your keys the way you would name a package: 'com.example.mylib.brand' or '@scope/pkg:brand'.
Anyone Can Forge It
A registered symbol is not a secret capability. Any code can call Symbol.for('com.example.mylib.brand') and stamp that brand onto an arbitrary object. Use registered symbols for cooperation between trusted code, never for access control. If you need an unforgeable token, use a local Symbol() and keep the reference to yourself.
Entries Are Not Freed
Each new key keeps its symbol alive as long as the runtime runs. Never build keys from dynamic data, such as Symbol.for('user:' + userId). That pattern leaks memory in a long-running server. Keep registry keys to a small, fixed set of constants.
Description Is Not a Registry Check
Do not use sym.description === 'app.theme' to decide whether you have "the" shared symbol. Compare identity (sym === Symbol.for('app.theme')) or use Symbol.keyFor.
Exercise
What does this code print, and why? const a = Symbol.for('x'); const b = Symbol('x'); console.log(a === b, a.description === b.description, Symbol.keyFor(b));
Show answer
It prints "false true undefined". Symbol('x') never consults the registry, so b is a new symbol distinct from the registered a. Both have the description "x", so the descriptions match. Symbol.keyFor(b) returns undefined because b is not registered.
Exercise
A plugin system tags plugin objects with Symbol('host.plugin') in host.js. Users report that plugins built against a second, bundled copy of host.js are rejected. What change fixes this, and what new risk does it introduce?
Show answer
Replace Symbol('host.plugin') with Symbol.for('com.example.host.plugin') so every copy of host.js, and every realm in the same agent, gets the same symbol. The new risk is that any code can now obtain the symbol by its key, so objects can be falsely tagged as plugins and an unrelated library using the same key would collide. A namespaced key reduces collisions, and the tag should not be treated as a security check.
Exercise
Why does Symbol.for(user.id) inside a request handler cause a memory problem, and why does Symbol.keyFor(Symbol.asyncIterator) return undefined?
Show answer
Every distinct key adds a registry entry that is never freed, because the symbol can always be recreated from its key. Keys made from user IDs grow without bound in a long-running process. Symbol.asyncIterator is a well-known symbol: it is shared across realms by the engine, but it is not stored in the global registry, so keyFor has no key to return.