Symbols
A symbol is a primitive value that is guaranteed to be unique: every call to Symbol() creates a new value that is equal to no other. Symbols are used as property keys that can't collide with any other key, whether yours, a library's, or one added to the language in the future. The language itself uses a set of well-known symbols such as Symbol.iterator to let your objects plug into built-in behavior like for...of. This lesson is optional on a first pass; you'll meet symbols again with iterators and classes.
In One Minute
Symbol("description")creates a unique value; the description is only a label for debugging.- Use symbols as object keys with brackets:
obj[key] = value,{ [key]: value }. - Symbol keys are skipped by
for...in,Object.keysandJSON.stringify, but they are not private. Symbol.for("name")returns a shared symbol from a global registry, the same one everywhere.- Well-known symbols (
Symbol.iterator,Symbol.toPrimitive,Symbol.toStringTag...) customize how objects behave with built-in operations.
Creating Symbols
const id1 = Symbol("id");
const id2 = Symbol("id");
console.log(typeof id1);
console.log(id1 === id2);
console.log(id1.description);
console.log(id1.toString());symbol
false
id
Symbol(id)Two symbols with the same description are still different values. The description exists only to make symbols readable in logs and debuggers. Symbols can't be created with new (new Symbol() throws), and they can't be implicitly converted to strings: "key: " + id1 throws a TypeError. Use String(id1) or id1.description.
Symbols as Property Keys
A symbol key can't collide with a string key, or with another symbol:
const internalId = Symbol("internalId");
const student = {
name: "Navika",
id: "S-001",
[internalId]: 4471,
};
console.log(student.id, student[internalId]);
console.log(Object.keys(student));
console.log(JSON.stringify(student));
for (const key in student) console.log("for...in:", key);
console.log(Object.getOwnPropertySymbols(student));S-001 4471
['name', 'id']
{"name":"Navika","id":"S-001"}
for...in: name
for...in: id
[Symbol(internalId)]Explanation: the symbol property sits alongside a string property named id without clashing. It is skipped by Object.keys, for...in and JSON.stringify, so it doesn't show up in ordinary loops or saved data. But Object.getOwnPropertySymbols (and Reflect.ownKeys) still find it.
Why Use Symbol Keys
The main reason is avoiding collisions when you add data to objects you don't fully control. If a library tagged objects with a string property like _meta, it could clash with your own _meta or another library's. A symbol key can't clash with anything:
const RECEIPT_SENT = Symbol("receiptSent");
function markSent(payment) {
payment[RECEIPT_SENT] = true;
}
const payment = { amount: 120, receiptSent: "custom field from the server" };
markSent(payment);
console.log(payment.receiptSent);
console.log(payment[RECEIPT_SENT]);custom field from the server
trueThe Global Symbol Registry
Symbol() always creates a new, unique symbol. Symbol.for(key) instead looks up a global registry: it returns the existing symbol for that key, or creates and registers one. The same key gives the same symbol anywhere in the program, even across modules, iframes or workers:
const a = Symbol.for("feeTracker.version");
const b = Symbol.for("feeTracker.version");
const c = Symbol("feeTracker.version");
console.log(a === b);
console.log(a === c);
console.log(Symbol.keyFor(a));
console.log(Symbol.keyFor(c));true
false
feeTracker.version
undefinedUse registered symbols when separate parts of a system must agree on a key without sharing a variable. Give the key a namespace (like "feeTracker.version") so it doesn't clash with other code using the registry.
Well-Known Symbols
The language defines built-in symbols, stored as properties of Symbol, that let your objects customize built-in behavior. They are called well-known symbols:
| Symbol | Customizes |
|---|---|
Symbol.iterator | How for...of, spread and destructuring iterate the object |
Symbol.asyncIterator | How for await...of iterates it |
Symbol.toPrimitive | How it converts to a primitive (see the type coercion lesson) |
Symbol.toStringTag | The tag in Object.prototype.toString ("[object Tag]") |
Symbol.hasInstance | How instanceof behaves |
Symbol.dispose, Symbol.asyncDispose | Cleanup with using (memory lesson) |
Making an Object Iterable
The most useful one: give an object a [Symbol.iterator] method, and for...of and spread work on it. A generator function (function*, covered in the generators lesson) is the easiest way to write one:
const feeSchedule = {
base: 400,
step: 15,
grades: [9, 10, 11, 12],
*[Symbol.iterator]() {
for (const grade of this.grades) {
yield { grade, fee: this.base + (grade - 9) * this.step };
}
},
};
for (const { grade, fee } of feeSchedule) {
console.log(`Grade ${grade}: $${fee}`);
}
console.log([...feeSchedule].length);Grade 9: $400
Grade 10: $415
Grade 11: $430
Grade 12: $445
4A Custom Type Tag
class FeeAccount {
get [Symbol.toStringTag]() {
return "FeeAccount";
}
}
console.log(Object.prototype.toString.call(new FeeAccount()));
console.log(String(new FeeAccount()));[object FeeAccount]
[object FeeAccount]In Practice
The Fee Tracker attaches cached totals to payment lists with a symbol key, so the cache never appears when the list is saved as JSON or looped over:
const CACHED_TOTAL = Symbol("cachedTotal");
function total(list) {
if (list[CACHED_TOTAL] === undefined) {
list[CACHED_TOTAL] = list.reduce((sum, p) => sum + p.amount, 0);
}
return list[CACHED_TOTAL];
}
const payments = [{ amount: 120 }, { amount: 85 }];
console.log(total(payments));
console.log(JSON.stringify(payments));
console.log(Object.keys(payments));205
[{"amount":120},{"amount":85}]
['0', '1']Common Mistakes
Using dot notation with a symbol. obj.mySymbol reads a string property named "mySymbol". Use obj[mySymbol].
Expecting symbol keys to be private. Object.getOwnPropertySymbols reveals them.
Joining a symbol into a string with +. It throws TypeError: Cannot convert a Symbol value to a string. Use String(sym) or sym.description.
Expecting Symbol("x") === Symbol("x"). Never true. Use Symbol.for("x") when you need the same symbol twice.
Practice
Challenge: Make a range object with from and to properties iterable with Symbol.iterator, so [...range] gives every whole number from from to to.
Show solution
const range = {
from: 3,
to: 7,
*[Symbol.iterator]() {
for (let n = this.from; n <= this.to; n++) yield n;
},
};
console.log([...range]);
console.log(Math.max(...range));[3, 4, 5, 6, 7]
7Key Takeaways
| Task | Code |
|---|---|
| Create | const s = Symbol("label") |
| Use as a key | obj[s] = 1, { [s]: 1 } |
| Shared symbol | Symbol.for("app.key") |
| List symbol keys | Object.getOwnPropertySymbols(obj) |
| Make iterable | *[Symbol.iterator]() { yield ... } |
Was this tutorial helpful?