Skip to content
jshacks.dev
Fundamentals

Symbols in JavaScript for Unique Keys and Well Known Hooks

A symbol is a unique primitive that works as a collision-proof property key, and well-known symbols hook objects into the language. See the rules and uses.

7 min read
Summarize in AI
Flat illustration of one event fanning out to several listeners, with the JavaScript, Node.js, Redis, Socket.io and TypeScript logos.

Strings are the default property key in JavaScript, and they collide. A library that stores metadata under the key "id" or "type" risks overwriting a value the application put there. A symbol is a key that cannot collide, because each one is unique by construction. That single property supports two uses: private-ish metadata on objects you do not own, and the well-known symbols through which the language lets you customize iteration, conversion and type checks. This post shows how symbols are created and compared, how they behave as keys, how the global registry differs, and the most useful well-known symbols, with output from Node.js 24 as an ES module. It builds on the seven primitive types, and the hooks it covers connect to iterators and iterables and object conversion.

Creating symbols

Symbol() takes an optional description, used only for debugging. Two symbols with the same description are different.

JavaScript
const a = Symbol("id");
const b = Symbol("id");

console.log(a === b);
console.log(typeof a);
console.log(a.toString(), a.description);
console.log(String(b));

try {
  console.log("key: " + a);
} catch (error) {
  console.log(error.name + ": " + error.message);
}

try {
  new Symbol("x");
} catch (error) {
  console.log(error.name + ": " + error.message);
}
Text
false
symbol
Symbol(id) id
Symbol(id)
TypeError: Cannot convert a Symbol value to a string
TypeError: Symbol is not a constructor

The two symbols look alike and are not equal. typeof reports "symbol". toString() and String() produce the text Symbol(id), and the description property gives the label alone. Implicit conversion to a string throws, which is deliberate: a symbol must not silently turn into a key that can collide. And new Symbol() is an error, since a symbol is a primitive and not an object.

Symbols as property keys

A symbol used as a key creates a property that does not clash with any string key and is skipped by the usual listing tools.

JavaScript
const secret = Symbol("secret");

const user = {
  name: "Ada",
  [secret]: "hidden value",
};

user[Symbol("other")] = "second";

console.log(Object.keys(user));
console.log(JSON.stringify(user));
console.log(user[secret]);
console.log(Object.getOwnPropertySymbols(user));
console.log(Reflect.ownKeys(user));

for (const key in user) {
  console.log("for...in:", key);
}

console.log({ ...user });
console.log(Object.assign({}, user)[secret]);
Text
[ 'name' ]
{"name":"Ada"}
hidden value
[ Symbol(secret), Symbol(other) ]
[ 'name', Symbol(secret), Symbol(other) ]
for...in: name
{
  name: 'Ada',
  Symbol(secret): 'hidden value',
  Symbol(other): 'second'
}
hidden value

Object.keys(), for...in and JSON.stringify() ignore the symbol keys, which makes them suitable for metadata that must not leak into serialization. Object.getOwnPropertySymbols() and Reflect.ownKeys() find them, so they are hidden from casual iteration, and not private. Spread and Object.assign() do copy symbol keys, which differs from JSON. That copying is why symbol keys survive a shallow clone but vanish in a JSON round trip, as covered in the post on shallow and deep copies.

The global registry

Symbol.for(key) looks up a symbol in a registry shared across the whole runtime, creating it if needed. Symbol.keyFor() reads the key back.

JavaScript
const first = Symbol.for("app.session");
const second = Symbol.for("app.session");
const local = Symbol("app.session");

console.log(first === second);
console.log(first === local);
console.log(Symbol.keyFor(first));
console.log(Symbol.keyFor(local));
console.log(Symbol.keyFor(Symbol.iterator));
Text
true
false
app.session
undefined
undefined

Two lookups of the same key give the same symbol, and a symbol made with Symbol() is never in the registry, so keyFor returns undefined for it. Well-known symbols are not registered either. Use Symbol.for() when two separate pieces of code, such as two copies of a library or two bundles, must agree on a key. Use plain Symbol() when the key is private to one module, which is the common case. Namespacing registry keys, as with "app.session", avoids accidental sharing.

Symbols as enum values

A frozen object of symbols makes constants that cannot be confused with arbitrary strings or numbers.

JavaScript
const Level = Object.freeze({
  INFO: Symbol("info"),
  WARN: Symbol("warn"),
  ERROR: Symbol("error"),
});

function label(level) {
  switch (level) {
    case Level.INFO:
      return "i";
    case Level.WARN:
      return "w";
    case Level.ERROR:
      return "e";
    default:
      throw new TypeError("unknown level: " + String(level));
  }
}

console.log(label(Level.WARN));
console.log(Level.WARN === Symbol("warn"));

try {
  label("warn");
} catch (error) {
  console.log(error.name + ": " + error.message);
}

console.log(JSON.stringify({ level: Level.WARN }));
Text
w
false
TypeError: unknown level: warn
{}

A string "warn" is rejected, which prevents a typo from passing as a valid level. The cost is serialization: a symbol-valued property is dropped by JSON.stringify(), so these constants cannot travel across a network or into storage. For values that cross a boundary, string constants are the right choice, and symbols suit internal, in-memory states only.

Well-known symbols

The language exposes a set of built-in symbols as static properties of Symbol. An object that defines one of them under that key takes part in the matching feature.

JavaScript
class Playlist {
  #tracks = ["intro", "verse", "outro"];

  *[Symbol.iterator]() {
    yield* this.#tracks;
  }

  get [Symbol.toStringTag]() {
    return "Playlist";
  }

  [Symbol.toPrimitive](hint) {
    return hint === "number" ? this.#tracks.length : this.#tracks.join(", ");
  }
}

const list = new Playlist();

console.log([...list]);
console.log(String(list));
console.log(+list);
console.log(Object.prototype.toString.call(list));

class Even {
  static [Symbol.hasInstance](value) {
    return Number.isInteger(value) && value % 2 === 0;
  }
}

console.log(4 instanceof Even, 5 instanceof Even);
Text
[ 'intro', 'verse', 'outro' ]
intro, verse, outro
3
[object Playlist]
true false

Symbol.iterator makes the object usable in spread and for...of. Symbol.toPrimitive controls what string and number conversion return, a mechanism explained in the post on converting objects to primitives. Symbol.toStringTag changes the label in Object.prototype.toString, which is also what shows in some debugging output. And Symbol.hasInstance lets a class decide what instanceof means, here turning a class into a predicate.

Other well-known symbols worth knowing are Symbol.asyncIterator for for await...of, Symbol.isConcatSpreadable for concat() as shown in the concat() post, and Symbol.species for the constructor that derived arrays use.

Async iteration and the other hooks

The same pattern gives an object asynchronous iteration. Defining Symbol.asyncIterator lets for await...of consume it, which is how streams and paginated sources are exposed.

JavaScript
class Pages {
  constructor(total) {
    this.total = total;
  }

  async *[Symbol.asyncIterator]() {
    for (let page = 1; page <= this.total; page++) {
      await Promise.resolve();
      yield { page, items: page * 10 };
    }
  }
}

for await (const result of new Pages(3)) {
  console.log(result);
}
Text
{ page: 1, items: 10 }
{ page: 2, items: 20 }
{ page: 3, items: 30 }

Each page was produced lazily, and the loop consumed them one at a time. The object itself is the iterable, and the generator method returns a fresh async iterator for each loop, so the same Pages instance can be consumed more than once. The post on iterators and iterables shows the protocol these hooks implement.

Metadata without collisions

The strongest everyday use is attaching data to objects owned by someone else. A string key can overwrite an existing property, and a symbol cannot.

JavaScript
const cacheKey = Symbol("cache");

function memoizeOn(object, compute) {
  object[cacheKey] ??= compute(object);
  return object[cacheKey];
}

const record = { id: 7, cache: "belongs to the app" };
let computations = 0;

const first = memoizeOn(record, (r) => (computations += 1, r.id * 100));
const second = memoizeOn(record, (r) => (computations += 1, r.id * 100));

console.log(first, second, computations);
console.log(record.cache);
console.log(Object.keys(record));
Text
700 700 1
belongs to the app
[ 'id', 'cache' ]

The cached result lives under a symbol, so the record's own cache property was left alone, Object.keys() does not list it, and a JSON dump of the record will not include it. The post on logical assignment explains the ??= operator used here. For private data that must not be reachable at all, a WeakMap or a private field is stronger, because symbol keys can still be found with getOwnPropertySymbols.

Debugging symbol-keyed data

Because symbol keys hide from the usual listing tools, a missing property in a log can be a symbol key you forgot. When an object seems to have less data than it should, print Reflect.ownKeys(object) and compare it with Object.keys(object). The difference is the symbol keys and the non-enumerable names. Node's util.inspect and most browser consoles show symbol keys in square brackets, so console.log(object) is often enough, as the first example shows, and JSON.stringify is the output that hides them. If data goes missing between a log and a payload, the serializer is where it was dropped.

Where symbols stop being the right tool

Do not use symbols for anything that must be serialized, logged as text or compared across processes. Do not use them as a security mechanism, since any code with the object can list its symbol keys. And do not reach for them when a plain string constant would do, because the debugging cost is real: a symbol prints as Symbol(label) and nothing more, and two symbols with the same label are indistinguishable in a log.

Symbols as WeakMap keys are allowed since ES2023 for unregistered symbols, which opens some patterns for private data, and runtime support is current in Node.js 20 and later.

Symbols are defined in the specification under the Symbol type and well-known symbols, and MDN's Symbol reference lists them with examples.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.