What is Symbol?

Symbol is a primitive type whose values are always unique; symbols are mainly used as property keys that cannot collide with any other key, and well-known symbols let you customise how built-in language features treat your objects.

Creating symbols

  • Symbol("description"): a new, unique symbol every time. The description is only a label for debugging.
  • Symbol.for("key"): a global registry symbol; the same key returns the same symbol everywhere, even across realms such as iframes.

Symbols as property keys

  • Guaranteed not to clash with string keys or other libraries' keys.
  • Hidden from for...in, Object.keys, and JSON.stringify. They are not private, though: Object.getOwnPropertySymbols and Reflect.ownKeys reveal them. (For real privacy, use #private fields.)

Well-known symbols

  • Symbol.iterator: makes an object iterable with for...of and spread.
  • Symbol.asyncIterator: for for await...of.
  • Symbol.toPrimitive: control conversion to numbers and strings.
  • Symbol.toStringTag: customise Object.prototype.toString output.
  • Symbol.hasInstance: customise instanceof.
  • Symbol.dispose / Symbol.asyncDispose: used by the using declarations from the explicit resource management proposal, which is rolling out in engines.

Use cases

Library metadata that will not collide with user properties, enum-like constants that cannot be confused with strings, and implementing language protocols like iteration.

Code example

js
1const id1 = Symbol("id");
2const id2 = Symbol("id");
3console.log(id1 === id2, typeof id1, id1.description); // false "symbol" "id"
4console.log(Symbol.for("app.version") === Symbol.for("app.version")); // true (global registry)
5
6// Collision-free, hidden-from-JSON keys
7const META = Symbol("meta");
8const user = { name: "Ada", [META]: { fetchedAt: 1700000000 } };
9console.log(Object.keys(user), JSON.stringify(user)); // ["name"] {"name":"Ada"}
10console.log(user[META].fetchedAt); // 1700000000
11console.log(Object.getOwnPropertySymbols(user).length); // 1 - discoverable, so not truly private
12
13// Enum-like constants that can't be mistaken for strings
14const Status = Object.freeze({ Active: Symbol("active"), Banned: Symbol("banned") });
15const check = (s) => (s === Status.Active ? "welcome" : "denied");
16console.log(check(Status.Active), check("active")); // welcome denied
17
18// Well-known symbols customise built-in behaviour
19class Range {
20 constructor(from, to) {
21 Object.assign(this, { from, to });
22 }
23 *[Symbol.iterator]() {
24 for (let i = this.from; i <= this.to; i++) yield i;
25 }
26 get [Symbol.toStringTag]() {
27 return "Range";
28 }
29}
30const r = new Range(1, 4);
31console.log([...r], Object.prototype.toString.call(r)); // [1, 2, 3, 4] "[object Range]"

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.

Open in study app