0
0
JavascriptConceptBeginner · 3 min read

What is Symbol in JavaScript: Unique Identifiers Explained

In JavaScript, a Symbol is a unique and immutable primitive value used as an identifier for object properties. It ensures property keys are unique, preventing name clashes in objects.
⚙️

How It Works

Think of a Symbol as a special, unique name tag that you can attach to an object property. Unlike strings, which can be repeated or accidentally overwritten, each Symbol is guaranteed to be unique, even if two symbols have the same description.

This uniqueness helps avoid conflicts when different parts of a program add properties to the same object. It’s like giving each property its own secret code that no one else can copy.

💻

Example

This example shows how to create symbols and use them as object property keys to keep properties unique and hidden from normal enumeration.

javascript
const sym1 = Symbol('id');
const sym2 = Symbol('id');

const user = {
  [sym1]: 123,
  name: 'Alice'
};

console.log(user[sym1]); // Access property with symbol key
console.log(sym1 === sym2); // false, symbols are unique

// Symbols do not show up in for...in loops
for (const key in user) {
  console.log(key); // only 'name' is logged
}

// But you can get symbols explicitly
console.log(Object.getOwnPropertySymbols(user));
Output
123 false name [ Symbol(id) ]
🎯

When to Use

Use Symbol when you want to add properties to objects without risking overwriting existing keys or causing conflicts. This is especially useful in large projects or libraries where many parts of code might add properties to the same object.

Symbols are also used to define special behaviors in objects, like customizing how objects convert to strings or how they respond to certain operations.

Key Points

  • Symbols are unique and immutable.
  • They can be used as object property keys.
  • Symbol properties do not appear in normal loops.
  • Useful to avoid property name conflicts.

Key Takeaways

Symbols create unique property keys that prevent name clashes in objects.
Each Symbol is different, even if they share the same description.
Symbol properties are hidden from normal object property loops.
Use Symbols to add safe, private-like properties or special behaviors to objects.