arrow_back
Back

JavaScript Symbol: unique keys and well-known symbols

Andrew Dorokhov Andrew Dorokhov schedule 1 min read
menu_book Table of Contents

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);
code

Need Help with Development?

Happy to help — reach out via the contacts or go straight to my Upwork profile.

work View Upwork Profile arrow_forward
Next Article

JavaScript Object: literals, properties, and spread

arrow_forward