Programozás The Wonderful Symbol

The Wonderful Symbol

What is the Symbol?

The symbol is a neat new data type of ES2015. It provides a new way to create unique identifiers in JAVASCRIPT.

How do symbols Work?

ES2015 has a factory function which creates a new symbol.

const mySymbol = Symbol();
// We can also give a string value to the factory function.
const mySymbolWithContent = Symbol(`nameKey`);

The difference between the two call ons below is the key. A key is an optional parameter which helps to find a symbol.

const s1 = Symbol(`symbol001`);
const s2 = Symbol(`symbol002`);
Symbol.for(`symbol001`); // output: Symbol(`symbol001`)

We can see that the Symbol object is able to find a Symbol instance by specifying a particular key.

Symbols are Always Unique

The browser JS engine registers all symbols and always creates a new one when the Symbol() function is called, even if they have the same key. If we compare two symbols, they won’t be equal.

const s3 = Symbol(`test`);
const s4 = Symbol(`test`);
s3 == s4 // output: false

Use Cases

Unique Object Key

Developers get confused when they have to name 100’s of variables in a day, but there’s an easy way to do that:

const writer = {};
const nameKey = Symbol(`key-for-name`);
writer[nameKey] = `Jack London`;

Create Hidden Properties

The for...in cycle and Object.keys method don’t see properties. Why? Because the property names created by a Symbol function are not a string. So, we can use symbols for hidden properties.

Object.keys(writer) // output: []

You start to use the Symbol function today ;)