Symbols as Object Keys
You'll learn how to use symbols as object property keys to avoid naming conflicts and create special internal properties.
Why Use Symbols as Keys?
When you use a string as an object property, there's always a risk someone else might use the same name. Symbols solve this by being guaranteed unique. Even if you create two symbols with the same description, they're different values, so they can't accidentally overwrite each other's properties.
Think of it like apartment keys: even if two keys look similar, each one is uniquely cut to open only its own lock. No one else can accidentally unlock your door.
Basic Syntax
const id = Symbol('id');
const user = {
name: 'Alice',
[id]: 12345 // using symbol as key
};
console.log(user.name); // 'Alice'
console.log(user[id]); // 12345
Notice the bracket notation [id] — that's how you use a symbol as a property key. You also need brackets when accessing it later.
Hidden from Enumeration
Symbol-keyed properties are non-enumerable in normal operations:
const secret = Symbol('secret');
const obj = {
visible: 'yes',
[secret]: 'hidden'
};
console.log(Object.keys(obj)); // ['visible'] — symbol key not shown
This makes symbols perfect for storing metadata or internal data that shouldn't appear when someone loops through an object's properties.
Collision-Free Properties
const myId = Symbol('id');
const theirId = Symbol('id');
const data = {
[myId]: 'A',
[theirId]: 'B'
};
console.log(data[myId]); // 'A'
console.log(data[theirId]); // 'B' — no conflict!
Key Takeaway: Symbols as object keys create unique, non-enumerable properties that won't conflict with string keys or other symbols, making them ideal for internal metadata.