Unique Keys, Forever
JavaScript Symbols
A symbol is a primitive whose only purpose is to be unique. Two symbols are never equal, even if they have the same description.
What you'll learn
- Create symbols with `Symbol()`
- Know that every symbol is unique
- Use symbols as object keys when you want guaranteed uniqueness
A symbol is a primitive value whose only feature is uniqueness.
Create one with Symbol(description). The description is for debugging
— it doesn’t affect equality.
const a = Symbol("id");
const b = Symbol("id");
console.log(a === a); // true
console.log(a === b); // false ← same description, different symbols
console.log(typeof a); // "symbol" Use Case: Unique Object Keys
Symbols make great object keys when you want to attach a property without colliding with anyone else’s keys.
const ID = Symbol("internal-id");
const user = {
name: "Ada",
[ID]: 42,
};
console.log(user.name); // "Ada"
console.log(user[ID]); // 42 Symbol-keyed properties don’t show up in Object.keys or for..in —
which is sometimes useful, sometimes a gotcha.
Well-Known Symbols
JavaScript reserves certain symbols for built-in protocols. The most useful one you’ll see:
Symbol.iterator— the key that makes an object iterable. We used this in the Iterables lesson.
const upToThree = {
[Symbol.iterator]() {
let n = 0;
return {
next() {
return n < 3 ? { value: n++, done: false } : { value: undefined, done: true };
},
};
},
};
for (const x of upToThree) console.log(x); // 0, 1, 2 Other well-known symbols include Symbol.asyncIterator,
Symbol.toPrimitive, Symbol.hasInstance — each customizes a
specific built-in behavior. You’ll meet them rarely.
When You Won’t Use Symbols
Honestly: in most everyday code, you won’t. Symbols solve specific problems (library API design, branding, well-known protocols) that don’t come up in app code often. Read this lesson, file it away, and recognize symbols when you see them in someone else’s library.
Up Next
Two object-like data structures with different tradeoffs — Map
and Set.