A Symbol is a primitive value that is guaranteed to be unique. No other value, not even another symbol with the same description, is ever equal to it. That makes symbols ideal as property keys that cannot clash with anyone else’s keys. JavaScript also has well-known symbols, special keys that let your own objects plug into built-in features such as for...of, type conversion and instanceof.
In this lesson you will learn
- Creating symbols and reading their description
- Using symbols as hidden property keys
- Shared symbols with
Symbol.for - Symbols as safe constants
- Well-known symbols:
Symbol.iterator,Symbol.toPrimitive,Symbol.toStringTagandSymbol.hasInstance
You should know data types, classes and iterators and generators.
Unique Keys and Constants
// Every Symbol() is unique, even with the same description
const id1 = Symbol("id");
const id2 = Symbol("id");
console.log(id1 === id2, id1.description, typeof id1);
// Symbol keys never clash with string keys or with other symbols
const user = { name: "Sadia", id: "public-42" };
const internalId = Symbol("id");
user[internalId] = 9001;
console.log(user.id, user[internalId]);
// Symbol keys are skipped by for...in, Object.keys and JSON
for (const key in user) console.log("for...in:", key);
console.log(Object.keys(user), JSON.stringify(user));
console.log(Object.getOwnPropertySymbols(user));
// Symbol.for shares one symbol across the whole program by name
const a = Symbol.for("app.theme");
const b = Symbol.for("app.theme");
console.log(a === b, Symbol.keyFor(a));
// Symbols make good constants: no two values can be equal by accident
const Status = Object.freeze({
ACTIVE: Symbol("active"),
BLOCKED: Symbol("blocked")
});
function describe(s) {
switch (s) {
case Status.ACTIVE: return "can log in";
case Status.BLOCKED: return "access denied";
default: return "unknown status";
}
}
console.log(describe(Status.ACTIVE), "|", describe("active"));
Output
false id symbol
public-42 9001
for...in: name
for...in: id
[ 'name', 'id' ] {"name":"Sadia","id":"public-42"}
[ Symbol(id) ]
true app.theme
can log in | unknown status
Symbol("id")creates a new symbol. The text is only a description for debugging, so two symbols with the same description are still different.- A symbol key lives alongside a string key with the same name:
user.idanduser[internalId]are separate properties. Use square brackets to read or write symbol keys. for...in,Object.keysandJSON.stringifyall skip symbol keys. This makes them good for extra data that should not show up in normal use.- Symbol keys are not truly private.
Object.getOwnPropertySymbolslists them. For real privacy, use#privateclass fields. Symbol.for("app.theme")looks the name up in a global registry and returns the same symbol every time.Symbol.keyForgives the name back.- Symbol constants such as
Status.ACTIVEcannot be confused with the plain string"active", so mistakes are caught.
Well-Known Symbols
// Well-known symbols let your objects plug into built-in features
class Money {
constructor(taka) { this.taka = taka; }
// Called whenever JavaScript converts the object to a primitive
[Symbol.toPrimitive](hint) {
if (hint === "number") return this.taka;
if (hint === "string") return `${this.taka} taka`;
return this.taka; // "default", e.g. with + or ==
}
// Changes the label shown by Object.prototype.toString
get [Symbol.toStringTag]() { return "Money"; }
}
const price = new Money(250);
console.log(`Price: ${price}`); // string hint
console.log(price * 2, price > 100); // number hint
console.log(price + 50); // default hint
console.log(Object.prototype.toString.call(price));
// Symbol.iterator makes an object work with for...of and spread
class Range {
constructor(from, to, step = 1) { Object.assign(this, { from, to, step }); }
*[Symbol.iterator]() {
for (let n = this.from; n <= this.to; n += this.step) yield n;
}
}
const evens = new Range(2, 10, 2);
console.log([...evens]);
for (const n of new Range(1, 3)) console.log("step", n);
// Symbol.hasInstance customises instanceof
class EvenNumber {
static [Symbol.hasInstance](n) { return Number.isInteger(n) && n % 2 === 0; }
}
console.log(4 instanceof EvenNumber, 7 instanceof EvenNumber);
Output
Price: 250 taka
500 true
300
[object Money]
[ 2, 4, 6, 8, 10 ]
step 1
step 2
step 3
true false
Symbol.toPrimitivecontrols how an object turns into a primitive. JavaScript passes a hint:"string"inside template literals,"number"for maths and comparisons, and"default"for+and==.Symbol.toStringTagchanges the name in[object Money], which helps when debugging.- A
*[Symbol.iterator]()generator method makesRangeiterable, so it works withfor...of, spread and destructuring. - A static
Symbol.hasInstancemethod decides whatinstanceofreturns. Use this rarely, because it can surprise other programmers.
| Well-known symbol | Used by |
|---|---|
Symbol.iterator | for...of, spread, Array.from, destructuring |
Symbol.asyncIterator | for await...of |
Symbol.toPrimitive | Conversion to number or string |
Symbol.toStringTag | Object.prototype.toString |
Symbol.hasInstance | instanceof |
Common Mistakes
- Writing
new Symbol(). Symbols are primitives, sonewthrows aTypeError. CallSymbol()directly. - Using dot notation, such as
user.internalId. That reads a string key called “internalId”, not the symbol. - Expecting symbol keys in JSON. They are left out, so send the data under string keys if the server needs it.
- Joining a symbol to a string with
+. This throws an error; useString(sym)orsym.description.
Practice Exercises
Exercise 1. Add a hidden createdAt symbol property to an object, and show that Object.keys does not list it.
Show answer
const createdAt = Symbol("createdAt");
const post = { title: "Hello" };
post[createdAt] = Date.now();
console.log(Object.keys(post)); // ["title"]
console.log(typeof post[createdAt]); // "number"
Exercise 2. Make a Playlist class with an array of songs, and make it iterable so [...playlist] gives the song names.
Show answer
class Playlist {
constructor(...songs) { this.songs = songs; }
*[Symbol.iterator]() { yield* this.songs; }
}
console.log([...new Playlist("Ami Banglay", "Ekla Cholo Re")]);
Frequently Asked Questions
Should I use symbols or #private fields to hide data?
Use #private fields for data that must stay inside a class, because outside code cannot reach them at all. Use symbols when other code should be able to use the key if it has the symbol, such as a library adding extra information to your objects.
Are symbols garbage collected?
Ordinary symbols are freed when nothing refers to them. Symbols made with Symbol.for live in a global registry for the whole program, so create them only for keys you really need to share.
Summary
- Every
Symbol()is unique; the description is only a label. - Symbol keys never clash with other keys and are skipped by
Object.keysand JSON. Symbol.forshares one symbol across a whole program.- Well-known symbols connect your objects to iteration, conversion and
instanceof.
