Global symbols in JavaScript

Using the Symbol.for method, you can create symbols with a name. These symbols will be stored in the global Symbol registry and can be retrieved from anywhere in the code.

Let's see how it works. Let's create a symbol in one function:

function func1() { let sym = Symbol.for('test'); return sym; }

Now in another function we will retrieve this symbol by its name:

function func2() { let sym = Symbol.for('test'); return sym; }

Let's check that both functions contain the same symbol. We call our functions:

let sym1 = func1(); let sym2 = func2();

And compare the symbols:

console.log(sym1 === sym2); // true

Suppose you have several objects. Add a key to each of them in the form of the symbol named 'sum'. Make a function in this key that will return the sum of the object elements.

enru