Sub topic 2
Sharing Symbols with the Global Registry
This chapter assumes you know how Symbol() creates unique values and how symbols work as property keys. It also assumes you are comfortable with classes, generators, for...of, and spread syntax.
Sharing Symbols with the Global Registry
Every call to Symbol() makes a new value. That causes a problem when two modules, or two realms such as an iframe and its parent page, need the same key. Symbol.for(key) fixes this. It looks up key in a runtime-wide registry and creates the symbol only if the key is not there yet.
const s1 = Symbol.for('app.theme');
const s2 = Symbol.for('app.theme');
console.log(s1 === s2); // true
console.log(Symbol.keyFor(s1)); // "app.theme"
console.log(Symbol.keyFor(Symbol('x'))); // undefinedSymbol.keyFor returns the registry key only for registered symbols. A common mistake is to assume that Symbol('app.theme') and Symbol.for('app.theme') are equal. They are not, because a description is only a label and has no effect on identity.
Well-Known Symbols: Hooks into the Language
Well-known symbols are built-in symbols stored as static properties of Symbol, such as Symbol.iterator. The engine looks for methods under these keys when it runs certain operations. If you define one of these methods on your object, you change how the language treats that object.
Making Objects Iterable with Symbol.iterator
for...of and spread call obj[Symbol.iterator]() and expect an iterator back. An iterator is an object with a next() method. A generator method is the shortest way to write one:
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
*[Symbol.iterator]() {
for (let i = this.start; i <= this.end; i++) {
yield i;
}
}
}
console.log([...new Range(1, 3)]); // [1, 2, 3]
for (const n of new Range(4, 5)) console.log(n); // 4, then 5Async Iteration with Symbol.asyncIterator
for await...of looks up Symbol.asyncIterator. An async generator gives you that method:
const ticker = {
async *[Symbol.asyncIterator]() {
yield 1;
yield 2;
}
};
(async () => {
for await (const n of ticker) {
console.log(n); // 1, then 2
}
})();Exercise
Module A runs const k = Symbol('cfg') and module B runs const k = Symbol.for('cfg'). Can B read a property that A stored under its k? Why or why not?
Show answer
No. Symbol('cfg') creates an unregistered symbol, so Symbol.for('cfg') returns a different registered symbol. Both modules need to call Symbol.for('cfg') to share the key.
Exercise
What does [...ticker] do with the ticker object above?
Show answer
It throws a TypeError. Spread looks up Symbol.iterator, and ticker defines only Symbol.asyncIterator.