What is ‘global symbol registry’?

var sym = Symbol();

is creating a new property sym in dictionary(window), which is in global scope, where value can be accessed as window['sym'].

Well, no. It does create a symbol and assigns it to a local variable named sym. Only if you are executing this code in the global scope (which you usually wouldn’t, for modularity) it does create a property on the global object of your realm (js environment). Notice that this global object is not always window like in web pages, it depends on your environment.

What is global symbol registry?

It’s a registry (think: dictionary) for symbols that you can access via a string key. And “global” does in this case mean even more global than a global scope, the global symbol registry does span all realms of your engine. In a browser, the web page, an iframe, and web worker would all have their own realm with own global objects, but they could share symbols via this global registry.

And this sharing is exactly the purpose. If you’d otherwise put

var sym1 = Symbol("shared");

var sym2 = Symbol("shared");

in two places, then sym1 !== sym2. If you’ve got a shared object, using the symbols as property keys would create two different properties. If however you do

var sym1 = Symbol.for("shared");

var sym2 = Symbol.for("shared");

then sym1 === sym2 and when you use it you’ll always get the same property.

See also Crossing realms with symbols on 2ality and Symbols and why they’re awesome for more examples, including the well-known symbols which are similarly global.

Leave a Comment