Understanding JavaScript Symbol
- A Unique Identifier
In JavaScript, Symbol("Siamak")
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 ("Siamak"
in this case), they will always be unique.
Key Points About Symbols
-
Creating a Symbol:
const mySymbol = Symbol("Siamak"); console.log(mySymbol); // Outputs: Symbol(Siamak)
-
Uniqueness:
Even if you do this:
const symbol1 = Symbol("Siamak"); const symbol2 = Symbol("Siamak"); console.log(symbol1 === symbol2); // Outputs: false
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: "Siamak", [symId]: 12345 // Symbol is used as a unique property key }; console.log(user); // Outputs: { name: 'Siamak', [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)
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
orObject.keys()
loops.
This makes symbols very useful for internal object properties that you want to stay hidden or unique.