Sub topic 3
Using Symbols as Collision-Free Property Keys
This chapter assumes you already know how to read and write object properties with dot and bracket notation, how computed property names ({ [expr]: value }) work, and how ES6 classes define methods. It also builds on the previous chapters: every call to Symbol() returns a new, unique value, and a symbol's description is only a label.
JavaScript property keys come in exactly two types: strings and symbols. Any other value you use as a key, such as a number, an object, or true, is converted to a string first. A symbol is never converted. It stays a symbol and identifies the property by its identity, not its spelling. That rule is what makes symbol keys collision-free.
The Problem: String Keys Collide
String keys are shared by everyone. If two pieces of code both decide to store something under "visited" on the same object, they overwrite each other, and neither one gets an error.
// Library A: marks a node as seen
function markVisitedA(node) {
node.visited = true;
}
function wasVisitedA(node) {
return node.visited === true;
}
// Library B: counts how many times a node was seen
function countVisitB(node) {
node.visited = (node.visited || 0) + 1;
}
const node = {};
markVisitedA(node);
countVisitB(node);
console.log(node.visited); // 2 (true + 1)
console.log(wasVisitedA(node)); // false, Library A is now brokenNeither library has a bug when you run it alone. The bug only shows up when both of them touch the same object, and that makes it hard to track down. Prefixes like __libA_visited make a collision less likely, but they cannot rule one out.
The Fix: One Symbol per Owner
If each library creates its own symbol, the keys cannot clash, even when the descriptions match.
// Library A
const visitedA = Symbol('visited');
function markVisitedA(node) {
node[visitedA] = true;
}
function wasVisitedA(node) {
return node[visitedA] === true;
}
// Library B
const visitedB = Symbol('visited');
function countVisitB(node) {
node[visitedB] = (node[visitedB] || 0) + 1;
}
const node = { visited: 'user data' };
markVisitedA(node);
countVisitB(node);
countVisitB(node);
console.log(wasVisitedA(node)); // true
console.log(node[visitedB]); // 2
console.log(node.visited); // "user data" (untouched)The object now holds three separate properties: the string key "visited" and two symbol keys. Each one can only be reached by code that holds the right key.
Every Way to Define a Symbol Key
You can only write a symbol key in places that accept an expression. Here are the forms you will use.
Bracket assignment
const id = Symbol('id');
const user = {};
user[id] = 42;
console.log(user[id]); // 42Computed keys in object literals
const id = Symbol('id');
const user = {
name: 'Ada',
[id]: 42,
};
console.log(user[id]); // 42Methods, getters, and setters
Computed keys also work in method shorthand, in accessors, and in class bodies.
const serialize = Symbol('serialize');
const size = Symbol('size');
class Point {
constructor(x, y) {
this.x = x;
this.y = y;
}
[serialize]() {
return `${this.x},${this.y}`;
}
get [size]() {
return Math.hypot(this.x, this.y);
}
static [serialize](point) {
return point[serialize]();
}
}
const p = new Point(3, 4);
console.log(p[serialize]()); // "3,4"
console.log(p[size]); // 5
console.log(Point[serialize](p)); // "3,4"Symbol-keyed methods in a class body live on Point.prototype, the same as string-keyed methods. Instances inherit them through the prototype chain.
Object.defineProperty
Use this form when you need control over the property attributes.
const version = Symbol('version');
const config = {};
Object.defineProperty(config, version, {
value: 3,
writable: false,
enumerable: false,
configurable: false,
});
console.log(config[version]); // 3
config[version] = 4; // silently ignored in sloppy mode
console.log(config[version]); // 3Destructuring
To read a symbol key while destructuring, you need a computed key and a new variable name.
const id = Symbol('id');
const user = { name: 'Ada', [id]: 42 };
const { [id]: userId, name } = user;
console.log(userId, name); // 42 "Ada"Ordinary Operators Work as Usual
Apart from how you write the key, symbol-keyed properties behave like any other property.
const tag = Symbol('tag');
const obj = { [tag]: 'blue' };
console.log(tag in obj); // true
console.log(Object.hasOwn(obj, tag)); // true
console.log(obj.hasOwnProperty(tag)); // true
delete obj[tag];
console.log(tag in obj); // falseInheritance also works. A symbol key on a prototype can be read through the instances:
const kind = Symbol('kind');
const base = { [kind]: 'animal' };
const dog = Object.create(base);
console.log(dog[kind]); // "animal"
console.log(Object.hasOwn(dog, kind)); // falseCopying: Spread and Object.assign Keep Symbol Keys
Developers often assume that symbol keys are dropped when an object is copied. Object spread and Object.assign both copy own, enumerable symbol-keyed properties.
const id = Symbol('id');
const hidden = Symbol('hidden');
const source = { name: 'Ada', [id]: 42 };
Object.defineProperty(source, hidden, { value: 'x', enumerable: false });
const spread = { ...source };
const assigned = Object.assign({}, source);
console.log(spread[id]); // 42
console.log(assigned[id]); // 42
console.log(spread[hidden]); // undefined (non-enumerable, not copied)So a symbol key does not keep your data inside its original object. If you attach a symbol to an object and the caller spreads it into a new object, your symbol goes with it. Usually that is what you want. If it is not, define the property as non-enumerable. Chapter 4 covers which APIs skip symbol keys, such as Object.keys and JSON.stringify.
Common Errors
Most bugs with symbol keys come from treating the symbol like a name instead of a value.
| Mistake | What happens | Fix |
|---|---|---|
| `obj.id` when the key is a symbol | Reads the string key `"id"`, returns `undefined` | Use `obj[id]` |
| `{ id: 42 }` in a literal | Creates the string key `"id"` | Use `{ [id]: 42 }` |
| `obj['Symbol(id)']` or `obj[String(id)]` | Reads a string key that only looks like the symbol | Use the symbol value itself |
| Calling `Symbol('id')` again to read the key | Gives a new, different symbol, returns `undefined` | Create the symbol once and reuse it |
| Not exporting the symbol from its module | Other modules cannot reach the property | Export the symbol, or use the registry (Chapter 5) |
| Adding a symbol key to a frozen object | Silently fails, or throws `TypeError` in strict mode | Store the data outside the object (Chapter 12) |
The fourth row is the one that catches people most often:
function setLabel(obj, value) {
obj[Symbol('label')] = value; // new symbol on every call
}
function getLabel(obj) {
return obj[Symbol('label')]; // another new symbol
}
const thing = {};
setLabel(thing, 'hello');
console.log(getLabel(thing)); // undefinedThe fix is to create the symbol once at module scope, where both functions can use it:
const label = Symbol('label');
function setLabel(obj, value) {
obj[label] = value;
}
function getLabel(obj) {
return obj[label];
}
const thing = {};
setLabel(thing, 'hello');
console.log(getLabel(thing)); // "hello"When a Symbol Key Is the Right Choice
Symbol keys fit best when code needs to put its own data on an object that other code also uses:
- A library attaching internal state or metadata to objects created by the user.
- A protocol method that other code is meant to find through a shared key, like
p[serialize]()above. This is the same idea the well-known symbols use, covered in Chapter 6. - Extending a built-in prototype or a third-party class without risking a clash with a future method of the same name.
Plain string keys are still the better choice for ordinary data that should serialize, show up in Object.keys, and be easy to read from a debugger or a log. Symbol keys protect you against accidental clashes. They do not protect against code that goes looking for them. Chapter 12 explains why that difference matters when you want privacy.
Exercises
Exercise
What does this code log, and why? const k = Symbol('k'); const o = { k: 1, [k]: 2 }; console.log(o.k, o[k], o['k']);
Show answer
It logs 1 2 1. The literal creates two properties: the string key "k" (from k: 1) and the symbol key k (from [k]: 2). o.k and o['k'] both read the string key, and o[k] reads the symbol key.
Exercise
A teammate writes const copy = { ...original }; and expects the symbol-keyed metadata from original to be gone in copy. When are they right, and when are they wrong?
Show answer
They are wrong for ordinary symbol properties created by assignment or in a literal. Those are own and enumerable, so spread copies them. They are right only if the property was defined as non-enumerable (for example with Object.defineProperty and enumerable: false) or if it is inherited from a prototype instead of being an own property.
Exercise
Rewrite function tag(obj) { obj[Symbol('seen')] = true; } function isTagged(obj) { return obj[Symbol('seen')] === true; } so that isTagged returns true for objects passed to tag.
Show answer
Create the symbol once and share it: const seen = Symbol('seen'); function tag(obj) { obj[seen] = true; } function isTagged(obj) { return obj[seen] === true; }. The original version creates a new, unique symbol on each call, so the read never matches the write.
Exercise
Inside an ES module, tag(Object.freeze({})) is called with the fixed tag function from the previous exercise. What happens, and what are two ways to handle it?
Show answer
Module code is strict, so assigning a new property to a frozen object throws a TypeError. You can check Object.isExtensible(obj) before tagging and skip or report the problem, or you can store the flag outside the object, for example in a WeakSet or WeakMap keyed by the object.