Symbols
Overview
A symbol is a primitive value that is guaranteed to be unique.
const a = Symbol('id');
const b = Symbol('id');
a === b; // false — same description, different symbolsThe text in brackets is only a description to help debugging — it shows up in the console as Symbol(id) and as a.description. It doesn’t make the symbol findable or comparable.
Symbols are the seventh primitive type (typeof a === 'symbol'). Their main job is to be property keys that can never collide with any other key.
Symbols as property keys
Because no other key can equal it, a symbol makes a property that can’t clash with anyone else’s:
const internal = Symbol('internal');
const lesson = { title: 'Symbols' };
lesson[internal] = { loadedAt: Date.now() };
Object.keys(lesson); // ['title'] — symbol keys are left out
JSON.stringify(lesson); // '{"title":"Symbols"}'This is useful for attaching metadata to objects you don’t own. If a library adds lesson.cache, and your code also adds lesson.cache, one overwrites the other. With a symbol, both can coexist.
Use computed property syntax to define a symbol key in an object literal or class:
const ID = Symbol('id');
const user = {
name: 'Asha',
[ID]: 42,
};
user[ID]; // 42
user.ID; // undefined — that's a string key called 'ID'Hidden, but not private
Symbol keys are skipped by Object.keys, Object.entries, for…in and JSON.stringify, so they stay out of the way. But they aren’t secret:
Object.getOwnPropertySymbols(lesson); // [Symbol(internal)]
Reflect.ownKeys(lesson); // ['title', Symbol(internal)]For genuinely private data, use class #private fields or closures.
Shared symbols
Symbol.for(name) returns the same symbol everywhere in your app for a given name:
Symbol.for('app.user') === Symbol.for('app.user'); // true
Symbol.keyFor(Symbol.for('app.user')); // 'app.user'These live in a global registry, so separate modules (or even iframes) can agree on a key without importing it from each other. Use a namespaced name like 'myapp.thing' to avoid clashes.
Well-known symbols
JavaScript uses built-in symbols to let your objects plug into language features:
| Symbol | Lets you customise |
|---|---|
Symbol.iterator |
how for…of and spread read your object |
Symbol.asyncIterator |
how for await…of reads it |
Symbol.toPrimitive |
how it converts to a number or string |
Symbol.toStringTag |
the name in [object …] |
Symbol.hasInstance |
how instanceof behaves |
const money = {
amount: 250,
[Symbol.toPrimitive](hint) {
return hint === 'number' ? this.amount : `₹${this.amount}`;
},
};
`${money}`; // '₹250'
+money; // 250toPrimitive receives a hint — 'string', 'number' or 'default' — telling it what kind of value JavaScript wants. Template literals ask for 'string'; maths operators ask for 'number'; + and == ask for 'default'.
Symbol.iterator
You met this in Iterators and generators. It’s the most useful well-known symbol: any object with a [Symbol.iterator] method works with for…of, spread and destructuring.
const week = {
*[Symbol.iterator]() {
yield* ['Mon', 'Tue', 'Wed', 'Thu', 'Fri'];
},
};
const [first, second] = week; // 'Mon', 'Tue'When to use symbols
In everyday application code you’ll rarely create symbols yourself. They shine when:
- you’re writing a library and need keys that can’t collide with users’ properties;
- you want to plug an object into language features (iteration, conversion);
- you need unique constants that can’t be confused with strings:
const Status = Object.freeze({
Idle: Symbol('idle'),
Loading: Symbol('loading'),
Done: Symbol('done'),
});
let status = Status.Idle;
status === 'idle'; // false — no accidental matches with plain stringsA tagged price
Give the price object a Symbol.toPrimitive method so that ${price} shows '₹499' and price * 2 gives 998. Then make it describe itself as [object Price] using Symbol.toStringTag.
const price = {
amount: 499,
// add the symbol methods here
};const price = {
amount: 499,
[Symbol.toPrimitive](hint) {
return hint === 'string' ? `₹${this.amount}` : this.amount;
},
get [Symbol.toStringTag]() {
return 'Price';
},
};
`${price}`; // '₹499'
price * 2; // 998
Object.prototype.toString.call(price); // '[object Price]'Summary
- Every
Symbol()is unique, even with the same description. - Symbol keys don’t clash with other properties and are skipped by
Object.keys,for…inand JSON. - Use computed keys
[sym]to define and read symbol properties. Symbol.for(name)returns a shared symbol for that name across your app.- Well-known symbols like
Symbol.iteratorhook into language features.