Computed Keys with Symbols
What you'll learn: How to use Symbol values as computed property keys to create unique, non-enumerable object properties.
Why Symbols Make Great Keys
You've learned that computed property keys let you dynamically create property names using brackets [expression]. Now here's where it gets powerful: when you combine computed keys with Symbols, you create properties that are:
- Guaranteed unique — no accidental name collisions
- Non-enumerable by default — they won't show up in
for...inloops orObject.keys()
Think of Symbols as secret compartments in your object. Regular property names are like labeled drawers everyone can see and open. Symbol keys are like hidden compartments that only those with the exact key can access.
Using Symbols as Computed Keys
const id = Symbol('id');
const metadata = Symbol('metadata');
const user = {
name: 'Alice',
[id]: 12345, // Symbol as computed key
[metadata]: {
created: '2024-01-01'
}
};
console.log(user.name); // 'Alice'
console.log(user[id]); // 12345
console.log(user[metadata]); // { created: '2024-01-01' }
// Symbol properties don't appear in normal enumeration
console.log(Object.keys(user)); // ['name'] - symbols excluded!
Notice you must use bracket notation [symbol] to access Symbol-keyed properties. Dot notation doesn't work because the property name isn't a string.
When This Pattern Shines
This is perfect for adding "internal" data to objects without polluting their visible interface. Libraries often use this to attach metadata that won't conflict with user-defined properties.
Key Takeaway: Combining computed keys with Symbols creates unique, hidden properties that avoid naming conflicts and stay out of normal object enumeration.