There's such a thing as registry symbol in JS ES6 (found in this Mozilla article).
It's different from the Symbol()
(relevant question on Stack Overflow), and can be obtained via Symbol.for(data)
.
Call
Symbol.for(string)
. This accesses a set of existing symbols called the symbol registry. Unlike the unique symbols defined bySymbol()
, symbols in the symbol registry are shared. If you callSymbol.for("cat")
thirty times, it will return the same symbol each time. The registry is useful when multiple web pages, or multiple modules within the same web page, need to share a symbol.
I've been searching info on this topic, I have read similar questions on Stack Overflow (there's What is 'global symbol registry'? but it doesn't cover the question - why use registry symbols instead of strings).
Although it seems that I have gotten (almost) everything about the unique symbols defined with Symbol()
, the registry symbols (Symbol.for()
) just don't make much sense at all for me.
I mean, look at the examples there:
Symbol.for('foo'); // create a new global symbol
Symbol.for('foo'); // retrieve the already created symbol
// Same global symbol, but not locally
Symbol.for('bar') === Symbol.for('bar'); // true
//ADDED BY ME
Symbol.for('far') === Symbol.for('bar'); // false
// The key is also used as the description
var sym = Symbol.for('mario');
sym.toString(); // "Symbol(mario)"
As far as I understand, the strings provide exact same functionality, don't they?
All those articles about saving/sharing symbols are unclear since saving and sharing is (at least seems to be!) essentially comparing the strings which are used to build the corresponding symbols.
What's the purpose of the registry symbols and how using them is different from using plain strings (i.e., I would like to see an example which I have failed to find)?