Symbol data type

Mateusz -

Symbol is a primitive data type, a new feature added in ES6. Container with a unique value inside it, something like unique ID. It is a primitive data type such as Number, String, Boolean.

Comparing Symbols

//
console.log(Symbol() === Symbol()); //false
console.log(Symbol(100) === Symbol(100)); //false
console.log(Symbol('Monkey') === Symbol('Monkey')); //false

const symbol1 = Symbol();
const symbol2 = Symbol(250); // 250 is description of this Symbol
const symbol3 = Symbol('Shrek'); // Shrek is description of this Symbol

console.log(symbol3); //Symbol(Shrek);
//

Comparing Symbols with the same value will give us a false result. This is because, as mentioned earlier, each Symbol is unique, so we cannot create two identical Symbols. When we log the variable that created our Symbol, we will get the description of that Symbol in return. Everything between brackets creating Symbol is called a “description” of that Symbol.

Key in Symbol

Using Symbols we can have keys that will be treated as an identifier for the Symbol. The for() method in Symbol allows us to search for Symbol with the exact key provided in for() method. If the for() method does not find the Symbol, it will create a new Symbol for us with a unique key. For searching Symbols using their keys we have keyFor() method.

//
const symbol4 = Symbol('Monkey');
const foundSymbol4 = Symbol.keyFor(symbol4);

console.log(foundSymbol4); //undefined

const symbol5 = Symbol.for('Monkey');
const foundSymbol5 = Symbol.keyFor(symbol5);

console.log(foundSymbol5); //Monkey
//

The result for constant foundSymbol4 will be undefined because the line before we created symbol4 using “description”. keyFor() method always look for a key.

We created the key “Monkey” in constant symbol5 using the for() method. So the next line, when we look for the key again, we get “Monkey” because the key was created using for() method.

Summary

Where we can use Symbol? It can be used primarily as an identifier for object properties.