A symbol or type Symbol represents some unique value.
A constructor of type Symbol is used to define a symbol. For example, let’s create a simple symbol:
const tom = Symbol("Tom"); console log(tom); // Symbol(Tom)
And each character is unique. So, let’s try to create two identical symbols:
const tom = Symbol("Tom"); console log(tom); // Symbol(Tom) const tomas = Symbol("Tom"); console log(thomas); // Symbol(Tom) console.log(tom == tomas); // false console.log(tom === tomas); // false
Despite the fact that both symbols created above in the prime are initialized with the same value, both equality and equivalence operators return when comparing these symbols false. That is, characters are always unique.
Symbols as object property identifiers
The main area of application of symbols is the definition of object property identifiers. That is, in short, symbols allow you to avoid situations where several properties of an object have the same name. Perhaps this situation may seem artificial: well, how can we define two identical properties in an object? However, if properties are added dynamically in a fairly large program, or even somewhere in external code that we have no control over, then the task of controlling property identifiers becomes more difficult.
For example, let’s take the following task: there are three programmers working in a company, one of which is a senior developer, and the other two are junior developers. But at the same time, two of the developers have the same names. Let’s say one Tom is a senior developer and Sam and another Tom are junior developers. For example, we could represent such a company like this:
const company = { "Tom": "senior", "Sam": "junior", "Tom": "junior" } for(developer in company) { console.log(`${developer} - ${company[developer]}`); }
However, the console output will show that there are only two developers in our company since the names of two of them are the same:
Tom-junior
Sam – junior
Now apply symbols:
const company = { [Symbol("Tom")]: "senior", [Symbol("Sam")]: "junior", [Symbol("Tom")]: "junior" } const developers = Object.getOwnPropertySymbols(company); for(developer of developers) { console.log(`${developer.toString()} - ${company[developer]}`); }
To get all the symbols from an object, the Object.getOwnPropertySymbols() function is used, into which the object is passed. This function returns a set of characters that we can loop through. You can use the symbol method to get the textual representation of characters toString(). And to get the value, as in the general case, the array syntax is used: company[developer]. As a result, we will get the following console output:
Symbol(Tom)-senior Symbol(Sam)-junior Symbol(Tom)-junior
You can also dynamically add properties with symbolic identifiers to an object:
const company = { }; company[Symbol("Tom")]= "senior"; company[Symbol("Sam")]= "junior"; company[Symbol("Tom")]= "junior";