Course contentsShow
← JavaScript
Lesson 1025 of 2,72323. SymbolsFree lesson

Symbol Registry for Cross-Realm Sharing

When and why to use Symbol.for() and Symbol.keyFor() for global symbol lookup.

Symbol Registry for Cross-Realm Sharing

You'll learn when and why to use Symbol.for() and Symbol.keyFor() to share symbols across different execution contexts.

The Cross-Realm Problem

Remember from earlier lessons that Symbol() creates unique symbols every time. But what if you're working with iframes, web workers, or different JavaScript realms where the same code runs in isolated environments? Regular symbols won't match across these boundaries, even if they have the same description.

Symbol.for() – The Global Registry

Symbol.for(key) creates or retrieves a symbol from a global symbol registry that spans all realms. Think of it like a phonebook that exists across different worlds—everyone can look up the same number using the same name.

// In your main window
const idMain = Symbol.for('app.id');

// In an iframe (different realm)
const idIframe = Symbol.for('app.id');

// These are THE SAME symbol!
console.log(idMain === idIframe); // true

Unlike Symbol(), Symbol.for() checks if a symbol with that key already exists globally. If yes, it returns the existing one. If no, it creates a new one and registers it.

Symbol.keyFor() – Reverse Lookup

Symbol.keyFor(symbol) lets you retrieve the registry key for a symbol created with Symbol.for():

const shared = Symbol.for('user.role');
console.log(Symbol.keyFor(shared)); // "user.role"

const local = Symbol('user.role');
console.log(Symbol.keyFor(local)); // undefined (not in registry)

When to Use This

Use the symbol registry when you need consistent symbol identity across different execution contexts—typically in libraries that might run in iframes or extensions that communicate across realms.

Key Takeaway: Symbol.for() creates globally-shared symbols across all JavaScript realms, while Symbol.keyFor() retrieves the registry key for shared symbols—use them when you need cross-realm symbol identity.