Symbols
A symbol is a primitive unique key. Two symbols are never equal, even if their descriptions match, which makes them safe as property names that will not collide with ordinary strings.
Detailed Explanation
Property keys in JavaScript are strings or symbols. Strings collide: if a library and your code both use "id", one write overwrites the other. A symbol is a unique identity. Symbol("id") === Symbol("id") is false. Each call creates a new symbol. The string is only a description for debugging.
You create a symbol with Symbol("description") or Symbol(). There is no new Symbol(); that throws. You use it as a key with computed property syntax: { [key]: value } and obj[key]. Dot notation cannot name a symbol.
Symbols do not show up in Object.keys, Object.values, JSON.stringify, or for...in. Object.getOwnPropertySymbols(obj) lists own symbol keys. Reflect.ownKeys(obj) lists string keys and symbol keys. This hidden-by-default behaviour is why people call them "private". They are not private. Anyone who can get the symbol value can read the property. Anyone who calls getOwnPropertySymbols can find the key. True privacy is #fields.
Well-known symbols are the ones the language uses as protocol hooks. Symbol.iterator makes an object iterable. Symbol.toStringTag customises Object.prototype.toString. Symbol.toPrimitive customises coercion. Symbol.hasInstance customises instanceof. Symbol.asyncIterator makes an object async-iterable. You do not create these; you use the ones on Symbol.
Global symbols live in a registry: Symbol.for("app.id") returns the same symbol every time for that string, across the realm. Symbol.keyFor(sym) returns the registry key. Use Symbol.for when two packages must share a key without importing the same module. Use Symbol("...") when you want a key that cannot be looked up by name.
What it costs you: invisibility. A forgotten symbol key does not appear in logs or JSON. Debugging means Object.getOwnPropertySymbols. Also, symbols are not JSON-serialisable as keys; they are dropped. Do not put user data behind a symbol if you need to persist it.
Reach for a symbol when you attach metadata to an object you do not own, or when you implement a language protocol. Reach for a string key when the property is part of your public data shape. Reach for #private when the property must be unreadable from outside the class.
Code Examples
const id = Symbol("id");
const user = {
email: "ada@example.com",
[id]: 7,
};
console.log(user[id]); // => 7
console.log(Object.keys(user)); // => [ 'email' ]
console.log(Object.getOwnPropertySymbols(user)); // => [ Symbol(id) ]
console.log(JSON.stringify(user)); // => {"email":"ada@example.com"}console.log(Symbol("id") === Symbol("id")); // => false
console.log(Symbol.for("id") === Symbol.for("id")); // => true
console.log(Symbol.keyFor(Symbol.for("id"))); // => idconst range = {
from: 1,
to: 3,
*[Symbol.iterator]() {
for (let n = this.from; n <= this.to; n += 1) {
yield n;
}
},
};
console.log([...range]); // => [ 1, 2, 3 ]Common Gotchas
`new Symbol()` throws
call `Symbol()` as a function. Symbols are primitives, not objects, unless you box them.
Symbols are hidden, not private
`Object.getOwnPropertySymbols` and `Reflect.ownKeys` reveal them. Use `#fields` for privacy.
`JSON.stringify` drops symbol keys
persist those fields under string names if they must survive a round trip.
`Symbol.for` is global to the realm
a shared name is a shared key. Typos create a second, unused symbol.