14. Symbol
A Symbol
is a unique and immutable data type introduced in ES6. The purpose of a symbol is to generate a unique identifier but you can never get any access to that identifier.
Here’s how you create a symbol:
const sym = Symbol("some optional description");
console.log(typeof sym); // symbol
Note that you cannot use new
with Symbol(…)
.
If a symbol is used as a property/key of an object, it’s stored in a special way that the property will not show up in a normal enumeration of the object’s properties.
const o = {
val: 10,
[Symbol("random")]: "I'm a symbol",
};
console.log(Object.getOwnPropertyNames(o)); // val
To retrieve an object’s symbol properties, use Object.getOwnPropertySymbols(o)