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:

  1. const sym = Symbol("some optional description");
  2. 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.

  1. const o = {
  2. val: 10,
  3. [Symbol("random")]: "I'm a symbol",
  4. };
  5. console.log(Object.getOwnPropertyNames(o)); // val

To retrieve an object’s symbol properties, use Object.getOwnPropertySymbols(o)