Sub topic 3
Using Symbols as Collision-Free Property Keys
This chapter assumes you know how to create a symbol with Symbol() and that every call returns a unique value. It also assumes you are comfortable with computed property names ({ [expr]: value }) and with ES6 classes.
The Problem: Shared Objects, Shared Names
Objects often pass through code that doesn't own them. A caching library, a logger, and your own app might all want to attach data to the same user object. If each one picks a string key such as id, the last write overwrites the others. Nobody gets an error.
A symbol key avoids this. A property key can be either a string or a symbol, and each symbol is unique. A library that creates its own symbol has a key that nothing else can produce by accident, even if another library uses the same description.
const user = { id: 7, name: 'Ada' };
// Two independent libraries each want to tag the object with an "id"
const cacheId = Symbol('id');
const trackerId = Symbol('id');
user[cacheId] = 'cache-91';
user[trackerId] = 'trk-3';
console.log(user.id); // 7
console.log(user[cacheId]); // "cache-91"
console.log(user[trackerId]); // "trk-3"The object now holds three separate properties. The string key "id" and the two symbol keys never touch each other.
Reading and Writing Symbol Keys
You can reach a symbol-keyed property only with bracket notation and the symbol value itself. Dot notation always uses a string key, which is the most common mistake people make with symbol keys.
const tag = Symbol('tag');
const obj = {};
obj.tag = 'string key'; // creates the string key "tag"
obj[tag] = 'symbol key'; // creates the symbol key
console.log(obj.tag); // "string key"
console.log(obj['tag']); // "string key"
console.log(obj[tag]); // "symbol key"Symbol keys also work in object literals, as class methods, and with Object.defineProperty:
const serialize = Symbol('serialize');
const version = Symbol('version');
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
[serialize]() {
return `${this.x},${this.y}`;
}
}
const p = new Point(1, 2);
Object.defineProperty(p, version, { value: 1, writable: false });
console.log(p[serialize]()); // "1,2"
console.log(p[version]); // 1
console.log('serialize' in p); // false
console.log(serialize in p); // trueThe in operator and hasOwnProperty accept symbols, so you can test for a symbol key just as you would for a string key.
Common Errors
| Mistake | What happens | Fix |
|---|---|---|
| `obj.mySym = 1` | Creates the string key `"mySym"` | Use `obj[mySym] = 1` |
| Calling `Symbol('id')` again to read the value | Creates a new, different symbol, so the read returns `undefined` | Store the symbol once and reuse that variable |
| `{ mySym: 1 }` in a literal | Creates the string key `"mySym"` | Use a computed key: `{ [mySym]: 1 }` |
| Expecting the description to find the property | The description is only a label | Keep a reference to the symbol |
When Symbol Keys Fit
Symbol keys work well when you add metadata or protocol methods to objects you don't control, and when your code can't predict which string keys other code will use. They prevent collisions. They don't hide data. Later chapters cover how reflection can still find symbol keys.
Exercise
A teammate writes const flag = Symbol('seen'); item.flag = true; and later checks item[Symbol('seen')], which returns undefined. Name both bugs and write the corrected lines.
Show answer
The first bug is that item.flag = true creates the string key "flag" and never uses the symbol. The second bug is that Symbol('seen') creates a new, different symbol, so the lookup can never match. The corrected lines are item[flag] = true; to write the value and item[flag] to read it, both using the same flag variable.
Exercise
Two plugins both store data with obj[Symbol('config')] = ..., each with its own symbol. Can one plugin overwrite the other's data? Does the string key obj.config change?
Show answer
Neither plugin can overwrite the other, because the two symbols are different keys even though their descriptions match. The string key obj.config stays untouched, because string keys and symbol keys are separate.