Lesson 86 - JavaScript Global Symbols with Symbol.for()
JavaScript provides a global symbol registry through the Symbol.for() method. This allows symbols to be shared across different parts of code, even across different files or modules.
What is Symbol.for()?
Symbol.for(key)searches the global symbol registry for a symbol with the given key.- If it exists, it returns that symbol.
- If it does not exist, it creates a new symbol and registers it globally with the given key.
const globalSym1 = Symbol.for("app.id");
const globalSym2 = Symbol.for("app.id");
console.log(globalSym1 === globalSym2); // true
Unlike
Symbol("desc"), which always creates a new symbol,Symbol.for("key")reuses a symbol if it already exists in the global registry.
Why Use Symbol.for()?
- Sharing symbols across modules or scopes
- Avoiding duplication when defining constants
- Creating a global contract for special property names
Retrieving the Key from a Global Symbol
You can retrieve the key (description) of a global symbol using Symbol.keyFor():
const sym = Symbol.for("user.token");
console.log(Symbol.keyFor(sym)); // "user.token"
Note: This works only with global symbols created using Symbol.for().
Symbol() vs Symbol.for()
| Feature | Symbol() |
Symbol.for() |
|---|---|---|
| Always unique? | Yes | No (shared via key) |
| Global registry? | No | Yes |
| Key retrievable? | No | Yes (Symbol.keyFor()) |
| Use case | Private/internal symbols | Shared/registered symbols |
Use Case Example
// In module A
const auth = Symbol.for("app.auth");
// In module B
const token = Symbol.for("app.auth");
console.log(auth === token); // true
Summary
Symbol.for()checks the global registry for existing keys.- It enables reuse of symbols globally.
- Use
Symbol.keyFor()to retrieve the key for global symbols. - Ideal for shared constants and avoiding key collisions in large apps.
Try Your Hand
Task:
Use Symbol.for() to create a global symbol for a property called "theme.color". Set a value using this symbol as a key in an object and retrieve it.
// Your solution here