Using Symbol.for to create a global instance
We've seen how to create unique symbols to use as keys in a local context. However, sometimes, we want to be able to interact with a data structure. Symbols can be made to work in this case as well.
Getting ready
This recipe assumes that you already have a workspace that allows you to create and run ES modules in your browser. If you don't, refer to the first two chapters.
How to do it...
- Open your command-line application and navigate to your workspace.
- Create a new folder named
11-02-symbol-for-global. - Copy or create an
index.htmlthat loads and runs amainfunction frommain.js. - Create a
main.jsfile that defines amainfunction that creates a couple of sets of Symbols, usingSymbol.for, with string and number arguments. Compare the numeric symbols with a number as string:
// main.js
export function main() {
const usLaunchLocation = Symbol.for('Kennedy Space Center');
const duplicateLaunchLocation = Symbol.for('Kennedy Space
Center');
...