Difficulty: Intermediate
What is a Symbol in JavaScript? How are Symbols used as property keys, and what are well-known Symbols?
A Symbol is a primitive type (added in ES2015) whose every value is unique: Symbol('id') !== Symbol('id'). Symbols are mainly used as property keys that cannot clash with string keys, and as well-known Symbols like Symbol.iterator that let your objects plug into built-in language behaviour such as for...of, type conversion and instanceof.
Symbol('description') creates a brand new, unique Symbol. The description is only a debugging label, readable through sym.description.Symbol.for('key') looks up a global registry shared across every realm in the page, including iframes. The same key always returns the same Symbol. Symbol.keyFor(sym) returns the key for registered Symbols.new Symbol() throws a TypeError; Symbols are primitives, not constructors.typeof sym is "symbol".Symbol-keyed properties are skipped by for...in, Object.keys, Object.entries and JSON.stringify. They are still reachable through Object.getOwnPropertySymbols(obj) and Reflect.ownKeys(obj), and Object.assign and object spread do copy them. So Symbols give you collision-free keys, not private ones. For real privacy use class #private fields or a WeakMap.
This is useful when you attach metadata to objects you do not own. A library can tag objects with obj[kTracked] = true without any risk of colliding with a user property called tracked. Node.js uses this pattern internally, for example util.inspect.custom is a registered Symbol (Symbol.for('nodejs.util.inspect.custom')).
| Symbol | Used by | What it customises |
|---|---|---|
Symbol.iterator | for...of, spread, destructuring, Array.from | How the object is iterated |
Symbol.asyncIterator | for await...of | Async iteration |
Symbol.toPrimitive | +obj, ` ${obj} , obj == x` | Conversion to number, string or default |
Symbol.toStringTag | Object.prototype.toString | The [object Tag] label |
Symbol.hasInstance | instanceof | Whether a value counts as an instance |
Symbol.species | map, filter on subclasses | Constructor used for derived objects |
Newer additions include Symbol.dispose and Symbol.asyncDispose for the explicit resource management proposal (using declarations), which shipped in recent V8 and TypeScript versions.
'id: ' + sym throws a TypeError. Use String(sym) or sym.description.WeakMap keys, but registered ones from Symbol.for cannot because they never get garbage collected.const id = Symbol('id');
const user = { name: 'Asha', [id]: 101 };
console.log(Symbol('id') === Symbol('id')); // unique every time
console.log(typeof id, id.description);
console.log(user[id]);
console.log(Object.keys(user)); // Symbol keys are skipped
console.log(JSON.stringify(user));
console.log(Object.getOwnPropertySymbols(user)); // but not hidden
console.log({ ...user }[id]); // spread copies them
// Global registry
console.log(Symbol.for('app.id') === Symbol.for('app.id'));
console.log(Symbol.keyFor(Symbol.for('app.id')));
try {
console.log('key: ' + id);
} catch (e) {
console.log(e.constructor.name);
}
Symbol keys stay out of Object.keys and JSON but are still discoverable, so they prevent collisions rather than guarantee privacy. Symbol.for shares one Symbol per key through the global registry.
class Range {
constructor(start, end) {
this.start = start;
this.end = end;
}
[Symbol.iterator]() {
let current = this.start;
const end = this.end;
return {
next() {
return current <= end
? { value: current++, done: false }
: { done: true };
}
};
}
}
const range = new Range(1, 5);
console.log([...range]);
for (const n of range) {
process.stdout.write(n + " ");
}
Symbol.iterator makes objects work with for...of loops and the spread operator.
class Money {
constructor(paise) { this.paise = paise; }
[Symbol.toPrimitive](hint) {
if (hint === 'number') return this.paise / 100;
return `Rs ${(this.paise / 100).toFixed(2)}`; // 'string' and 'default'
}
get [Symbol.toStringTag]() { return 'Money'; }
}
const price = new Money(49900);
console.log(+price); // hint: number
console.log(`${price}`); // hint: string
console.log(Object.prototype.toString.call(price));
Symbol.toPrimitive receives a hint telling you which conversion the engine wants. Symbol.toStringTag changes the label used by Object.prototype.toString, which some type-checking utilities rely on.
Symbol, Symbol.for, Well-Known Symbols, Symbol.iterator, Symbol.toPrimitive