Glossary / Symbols

Symbols

A Symbol is a unique primitive value commonly used as an object property key. Symbol("id") creates a new identity every time, even when descriptions match. Symbols help libraries add metadata or protocol hooks without colliding with ordinary string-named properties, but they are not private or secret: reflection APIs can discover symbol properties.

Identity, registry, and enumeration

const first = Symbol("id");
const second = Symbol("id");
first === second; // false

const metadata = Symbol("metadata");
const item = { name: "part", [metadata]: 12 };
Object.keys(item); // ["name"]
Reflect.ownKeys(item); // includes metadata

Symbol.for(key) uses a global symbol registry and returns the same registered Symbol for a key within the relevant agent; Symbol.keyFor retrieves a registered key. This differs from locally created Symbols. Descriptions aid debugging but do not affect equality. JSON serialization ignores Symbol-keyed properties, and Object.keys omits them; use Object.getOwnPropertySymbols or Reflect.ownKeys for inspection.

Symbols convert explicitly to strings with String(symbol), but implicit string concatenation can throw. Symbols cannot be converted to Number. Well-known Symbols such as Symbol.iterator define language protocols.

When to use them

Symbols are useful for non-colliding library metadata or implementing protocols. Use #private for class-enforced private fields; a symbol property is discoverable and can be copied by reflective code. Avoid replacing clear string keys with symbols if ordinary data inspection and JSON interchange are important.

Interview questions

  1. Are two Symbols with the same description equal? No; each Symbol() call has unique identity.
  2. Are Symbol properties private? No; reflective APIs can enumerate them.
  3. What does Symbol.for do? It obtains a shared registered Symbol for a key.
  4. Why does Object.keys omit symbols? It returns own enumerable string keys only.

References