Javascript - Symbols and Registry

Introduction

Symbols can be placed in a global registry, from where they can be accessed across different contexts known as realms.

A realm is a context in which pieces of code exist.

Symbols come with a special power to be available throughout the runtime-wide symbol registry.

You can use the following methods to add symbols to the runtime-wide symbol registry:

Symbol.for(key) and Symbol.keyFor(symbol). 

Symbol.for(key)

This method looks up existing symbols in the runtime-wide symbol registry with the given key.

If a symbol with that key exists in the global registry, that symbol is returned.

If no symbol with that key is found in the registry, a new symbol gets created.

For example, the first call to Symbol.for('myCar') creates a symbol, adds it to the registry, and returns it.

And the second call returns that same symbol because the key is already in the runtime-wide symbol registry:

Symbol.for('myCar') === Symbol.for('myCar') // true 

The runtime global registry keeps track of all the symbols created using Symbol.

for(key) method can be accessed across different realms.

Symbol.keyFor(symbol)

Symbol.keyFor(symbol) retrieves the key from the global symbol registry when the symbol was added to the registry.

It returns undefined when the symbol is not found in the registry.

const symbol = Symbol.for('myHouse'); 
console.log(Symbol.keyFor(symbol)); // myHouse 
const myCat = Symbol(); 
Symbol.keyFor(myCat); // undefined 

Related Topic