CodeBlanks Logo Icon CodeBlanks

Symbol.for and Symbol.keyFor

JavaScript course · Advanced · Lesson 67/100

Learn to get a symbol from the global registry and find its key.

The global symbol registry

Symbol() produces a fresh symbol every call. But sometimes you want to share the same symbol across different parts of your code, identified by a string key.

Symbol.for('key') first looks up that key in the global registry. If found, it returns the existing symbol; otherwise it creates one, stores it, and returns it. So Symbol.for('app') called twice returns the same symbol. These symbols are shared across the whole application.

Symbol.keyFor

Symbol.keyFor(symbol) does the reverse: given a symbol from the registry, it returns its key string. So Symbol.keyFor(Symbol.for('token')) returns 'token'.

If the symbol was created with Symbol() (not through the registry), Symbol.keyFor returns undefined. This makes it easy to tell whether a symbol is shared or local.

Exercise Use a shared symbol

Get a symbol with Symbol.for('config') into a variable first. Log its key using Symbol.keyFor(first). Then call Symbol.for('config') again into a variable second and log the comparison first === second.

Show example solution
const first = Symbol.for('config');
console.log(Symbol.keyFor(first));
const second = Symbol.for('config');
console.log(first === second);

Test yourself

  1. What happens if Symbol.for('app') is called twice?

    • A new symbol is created each time
    • The first call throws an error
    • The same symbol is returned and they are equal
    • It returns undefined
    Show answer

    The same symbol is returned and they are equal — Correct. Symbol.for first checks the registry; if the key exists, it returns the stored symbol.

  2. Create a shared symbol

    const shared = ____;
    Show answer
    const shared = Symbol.for('token');
  3. Symbol.for and Symbol.keyFor

    Symbol.for('x')
    Reads or creates from the registry
    Symbol.keyFor(sym)
    Returns the symbol's key
    Symbol('x')
    Always unique
    Not in registry
    keyFor returns undefined

All lessons in Advanced