JavaScript Reference ยท Iterators, Generators and Symbols
Symbol.for()
Reference for JavaScript Symbol.for() and Symbol.keyFor(): create or look up shared symbols in the global registry, with examples, edge cases and usage notes.
Symbol.for(key) returns a symbol from a global registry. The first call with a given key creates the symbol and stores it; every later call with the same key returns that same symbol. This is different from Symbol(), which creates a brand-new, unique symbol each time.
The registry is shared across the whole realm, so two scripts that never import each other can still agree on a symbol just by using the same string. The companion method Symbol.keyFor(symbol) goes the other way and returns the key of a registered symbol.
const id = Symbol.for("app.id"); Symbol.for("app.id") === id; // true Symbol.keyFor(id); // "app.id"
Try it
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Press Run (or Ctrl + Enter) to see the console output here.
No output.
Syntax
Symbol.for(key) Symbol.keyFor(sym)
| Name | Description |
|---|---|
key |
Any value. It is converted to a string, so 42 and "42" name the same symbol, and a missing argument gives the key "undefined". |
sym |
For Symbol.keyFor(): the symbol to look up. |
Return value: Symbol.for() returns the registered symbol. Symbol.keyFor() returns the key string, or undefined if the symbol was not created through the registry.
Exceptions: Symbol.for() throws a TypeError when key is a symbol, because a symbol cannot be converted to a string. Symbol.keyFor() throws a TypeError when its argument is not a symbol.
Usage notes
- Registered symbols are shared. Use them when separate pieces of code, libraries or frames of the same realm must find the same property key without passing the symbol around.
- Pick a namespaced key. Anyone can call
Symbol.for("id"), so collisions are possible. A prefix such as"my-lib.id"makes accidents unlikely. - The description equals the key.
Symbol.for("x").descriptionis"x". - Well-known symbols are not registered.
Symbol.keyFor(Symbol.iterator)isundefined, andSymbol.for("Symbol.iterator")is a different symbol. - Registered symbols are never collected. The registry keeps them alive, so do not generate keys from user input or in a loop.
- The registry spans realms. A same-origin iframe and its parent page get the same symbol for the same key, whereas symbols made with
Symbol()are never equal across realms. - Not a secret. Properties keyed by a registered symbol are hidden from
Object.keys()andJSON.stringify(), butObject.getOwnPropertySymbols()andReflect.ownKeys()still reveal them. - For truly private state use a private class field (
#field) or a module-localSymbol().
Browser support
Symbol.for() and Symbol.keyFor() work in every current browser and in Node.js.