JavaScriptFundamental (ES6), part 2
Symbol() vs Symbol.for() in JavaScript
69 Symbol.for and the global registry
fairSymbol() gives a key nobody else can produce. Symbol.for() gives one everybody can. Show that two Symbol.for calls with the same string are the same key, that a value stored under one is readable by code that never saw it, that Symbol.keyFor distinguishes the two kinds, and that the well-known symbols are not in the registry at all.
Stuck? Three hints, smallest first
- 1.
Symbol.for(key)looks in a process-wide table and only creates a symbol if the key is new. - 2.
Symbol.keyForanswersundefinedfor anything that did not come from the registry. - 3. A description is a label. Two symbols can share one and still be different keys.
const registered = Symbol.for('gradsphere.audit');
const again = Symbol.for('gradsphere.audit');
const local = Symbol('gradsphere.audit');
const sameKey = registered === again;
const differentKey = registered === local;
const keys = [Symbol.keyFor(registered), Symbol.keyFor(local)];
const state = {};
state[registered] = 'Balogun till 3';
state[local] = 'Ikeja till 1';
// Code over here never saw the symbols above, and only one of the two is reachable.
const reachable = state[Symbol.for('gradsphere.audit')];
const unreachable = state[Symbol('gradsphere.audit')] === undefined;
const bothStored = Object.getOwnPropertySymbols(state).length;
const printIdentically = [String(registered), String(local)];
const descriptions = [registered.description, local.description];
const wellKnown = [Symbol.keyFor(Symbol.iterator), Symbol.keyFor(Symbol.toStringTag)];
const iteratorIsGlobalAnyway = Symbol.iterator === Symbol.iterator;
const flatNamespace = Symbol.for('audit') === Symbol.for('gradsphere.audit');
const emptyKeyWorks = Symbol.keyFor(Symbol.for(''));
console.log('same key, different key:', sameKey, differentKey);
console.log('keyFor :', keys);
console.log('reachable from nowhere :', reachable);
console.log('both print as :', printIdentically);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('two Symbol.for calls with the same string are one symbol', sameKey, true);
test('a Symbol() with the same description is a different key entirely', differentKey, false);
test('keyFor round-trips a registry symbol and refuses a local one', keys, ['gradsphere.audit', undefined]);
test('so a registry key reaches the value without the symbol being shared', reachable, 'Balogun till 3');
test('while the local key is unreachable, though the value is still there', [unreachable, bothStored], [true, 2]);
test('both print identically and share a description: text cannot tell them apart', [printIdentically, descriptions], [['Symbol(gradsphere.audit)', 'Symbol(gradsphere.audit)'], ['gradsphere.audit', 'gradsphere.audit']]);
test('the well-known symbols are global but not in the registry', [wellKnown, iteratorIsGlobalAnyway], [[undefined, undefined], true]);
test('the registry is one flat namespace, which is why real keys are prefixed', flatNamespace, false);
test('and even an empty string is a valid registry key', emptyKeyWorks, '');
Two mechanisms that look alike and mean opposite things. Symbol('x') is for a key you own: nobody can collide with it, and nobody can reach your value without the symbol itself. Symbol.for('x') is for a key you want others to reach — a protocol. The fourth and fifth assertions are that difference in one object: both values are on state, and only the registered one can be looked up from code that never saw the symbol.
The registry is per realm-group, not per module, which is the point: two copies of a library bundled twice, or a library and a page script, agree on Symbol.for('react.element') without importing anything from each other. That is why the last-but-two assertion matters — one flat namespace, no scoping, so a bare key like 'audit' is a collision waiting to happen. Prefix with something you own.
Two things people expect and do not get. Registry symbols are never collected: the table holds them for the life of the realm, so Symbol.for in a loop over user input is a leak. And the well-known symbols — Symbol.iterator and friends — are not registry entries, so Symbol.keyFor(Symbol.iterator) is undefined even though the symbol is shared by everything; they are their own separate kind of global.
The sixth assertion is the one to keep in mind while debugging. Two symbols with the same description print the same, log the same and describe the same, and are still different keys. If a symbol-keyed lookup is missing a value, comparing the text tells you nothing.