Dorokhov.codes

Symbol

A Symbol is a unique, immutable primitive value introduced in ES6. It is often used as a key for object properties to ensure the key is unique and avoid collisions with other properties.

Every Symbol is guaranteed to be unique, even if created with the same description.

const sym1 = Symbol("desc");
const sym2 = Symbol("desc");
console.log(sym1 === sym2); // false

Symbols can be used as object property keys.

const sym = Symbol("key");
const obj = { [sym]: "value" };
console.log(obj[sym]); // "value"

Symbol Registry

Use Symbol.for() to create or retrieve a shared symbol from the global symbol registry.

const sym1 = Symbol.for("shared");
const sym2 = Symbol.for("shared");
console.log(sym1 === sym2); // true

Getting object property symbols

Use the next method:

Object.getOwnPropertySymbols(obj);