DEV Community

Cover image for Understanding JavaScript Symbol - A Unique Identifier
Alex Beygi
Alex Beygi

Posted on

Understanding JavaScript Symbol - A Unique Identifier

In JavaScript, Symbol("Alex") is a way to create a unique identifier.

Symbols are a special data type in JavaScript. Even if you create two symbols with the same description ("Alex" in this case), they will always be unique.

Key Points About Symbols
Creating a Symbol:

const mySymbol = Symbol("Alex");
console.log(mySymbol); // Outputs: Symbol(Alex)
Enter fullscreen mode Exit fullscreen mode

Uniqueness:

Even if you do this:

const symbol1 = Symbol("Alex");
const symbol2 = Symbol("Alex");
console.log(symbol1 === symbol2); // Outputs: false
Enter fullscreen mode Exit fullscreen mode

The two symbols are different, even if they have the same description.

Why Use Symbols?

Object Properties: Symbols can be used as unique keys for object properties. They avoid naming conflicts because no two symbols are the same.

They are useful for creating "hidden" properties that won't conflict with other keys.

Practical Example: Avoiding Key Conflicts
Here's how to use a Symbol to avoid property name conflicts in an object.

// Example with Symbols
const symId = Symbol("id");

const user = {
   name: "Alex",
   [symId]: 12345 // Symbol is used as a unique property key
};

console.log(user); 
// Outputs: { name: 'Alex', [Symbol(id)]: 12345 }

// Accessing the Symbol property
console.log(user[symId]); // Outputs: 12345

// Another script cannot accidentally overwrite this property:
user["id"] = 67890; // Regular key
console.log(user.id); // Outputs: 67890 (regular key)
console.log(user[symId]); // Still Outputs: 12345 (symbol key is untouched)
Enter fullscreen mode Exit fullscreen mode

Key Benefits
Symbols Prevent Key Overlaps: The Symbol key (symId) and the regular string key ("id") don't clash.

Hidden Properties: Symbols don't show up in regular for...in or Object.keys() loops.

This makes symbols very useful for internal object properties that you want to stay hidden or unique.

Top comments (0)