JavaScript Symbols Explained

JavaScript Logo

Introduced in ES6, the `Symbol` is a primitive data type that is guaranteed to be unique and immutable. This uniqueness makes Symbols very useful for specific purposes.

Creating Symbols

You create a Symbol by calling the `Symbol()` function. You can provide an optional description for debugging purposes, but this description does not affect its uniqueness.

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

console.log(sym1 === sym2); // false - every symbol is unique

Primary Use Case: Unique Object Properties

The main reason for Symbols is to create unique property keys for objects. This prevents accidental name collisions between properties, which is especially important when adding properties to objects you don't own (like third-party library objects).

const ID = Symbol('id');

const user = {
  name: 'Alice',
  [ID]: 123 // Using a symbol as a property key
};

console.log(user[ID]); // 123

// Symbol properties are not included in for...in loops or Object.keys()
for (let key in user) {
  console.log(key); // only 'name'
}

This 'hidden' nature makes Symbols ideal for adding metadata to objects without interfering with normal operations.

Comments