Symbols and Well-Known Symbols

Advanced · 12 min

`Symbol` as a primitive that never collides, why that makes it a useful property key, and how "well-known" symbols hook into built-in behavior.

Before thisObjects and Property Descriptors

Colt Steele · 12 min

Symbols and Well-Known Symbols

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Colt SteeleReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A `Symbol()` call always returns a brand-new, unique value — even two symbols created with the exact same description string are never equal to each other — which is the one guarantee that makes them useful as property keys that can't accidentally collide with anyone else's.
  • Symbol-keyed properties are skipped by `for...in`, `Object.keys`, `JSON.stringify`, and most everyday object inspection, so they work well for attaching metadata to an object without that metadata showing up where regular string keys would.
  • Well-known symbols are specific symbols the engine itself already holds a reference to (`Symbol.iterator`, `Symbol.toPrimitive`, `Symbol.toStringTag`, and others) — defining a method at one of those keys is how your own object opts into built-in language behavior like `for...of` or the `+` operator, instead of the engine refusing to know what to do with it.
  • `Symbol.for(key)` looks a value up in a global, engine-wide registry instead of minting a new unique symbol — the one case where you deliberately want the *same* symbol back across different parts of a codebase, or even different realms.
  • Symbols solve a narrower problem than most language features you've met so far — expect to reach for them rarely, but recognize them instantly when you see `[Symbol.iterator]` in someone else's code.

The problem a new primitive type had to solve

By the time ES6 shipped, JavaScript had a quiet problem: every object property key was either a string or (after coercion) turned into one. That’s fine until two independent pieces of code — your app and a library, or two libraries — both decide to stash something on the same object under a key like "id" or "metadata". Whoever writes second silently overwrites whoever wrote first. Strings are great for keys you want other code to find and use; they’re terrible for keys you want to guarantee nobody else will ever accidentally reuse.

Symbol exists to solve exactly that. It’s a primitive type — alongside string, number, boolean, and the others — whose only defining feature is that every value it produces is unique. Call Symbol() twice, a thousand times, from anywhere in your program, and you will never get the same value back. That one guarantee is the whole feature.

Creating and using symbols

const id = Symbol('user id');
const otherId = Symbol('user id');

id === otherId; // false — same description, different symbol

const user = {
  name: 'Ada',
  [id]: 42,
};

user[id]; // 42
Object.keys(user); // ["name"] — the symbol key doesn't show up here

The string you pass to Symbol() — 'user id' above — is purely a debugging label. It shows up if you console.log the symbol or inspect it, but it plays no role in equality or lookup. Two symbols with the same description are still two completely different values.

That invisibility to Object.keys, for...in, and JSON.stringify is the other half of why symbols get used as property keys: they’re a place to put data on an object that won’t leak into the paths most code uses to iterate over “the object’s properties.” Libraries use this to attach internal bookkeeping to objects you hand them without worrying about clashing with your own fields, or having that bookkeeping show up when you serialize the object.

If you deliberately want the same symbol in two different places without passing a reference around, Symbol.for('some-key') is the escape hatch — it reads from (and writes to, on first call) a global registry keyed by that string, so every call with the same key after the first returns the identical symbol.

Well-known symbols: hooking into the language itself

Here’s the part that makes symbols more than a collision-avoidance trick. The language has its own fixed set of symbols — called well-known symbols — that it already holds references to internally, and checks for on objects at very specific moments. Defining a property at one of these keys is how you plug your own object into built-in behavior that would otherwise have no idea what to do with it.

The one you’ll meet constantly: Symbol.iterator. When you write for (const x of thing), or spread something with [...thing], the engine doesn’t have special-case logic for arrays, strings, and Maps — it just calls thing[Symbol.iterator]() and expects back an iterator object. Arrays and strings already have that method built in. Give your own object one, and for...of works on it too, with no engine changes required:

const range = {
  from: 1,
  to: 3,
  [Symbol.iterator]() {
    let current = this.from;
    const last = this.to;
    return {
      next() {
        return current <= last
          ? { value: current++, done: false }
          : { value: undefined, done: true };
      },
    };
  },
};

[...range]; // [1, 2, 3]

A second one worth knowing by name: Symbol.toPrimitive. It controls what an object becomes when something forces it down to a primitive — +obj, template-literal interpolation, obj + 1. Define a function there and you decide the output yourself instead of relying on the default toString / valueOf fallback chain. Others exist for narrower jobs — Symbol.toStringTag changes what Object.prototype.toString.call(x) reports, Symbol.hasInstance lets a class customize what instanceof returns for it — but the shape is always the same: the engine looks for a specific symbol key, and if your object has defined one, your code runs instead of the default.

How the embedded video fits in

The embedded video walks through Symbol from the ground up — creating them, using them as property keys, and a few concrete use cases — which covers the uniqueness guarantee and the “property key that can’t collide” angle solidly. It doesn’t dedicate time to the well-known symbols specifically, so that half of this lesson’s scope leans on the explanation above; the two short “go deeper” videos each zoom in on one well-known symbol — Symbol.iterator and Symbol.toPrimitive — if you want to see them demonstrated on their own.

Where this fits in the path

This comes right after objects and property descriptors, because a symbol is really a new kind of key, not a new kind of object — everything you already know about property access still applies. From here, the next lesson, proxies, uses one of these well-known symbols directly: a Proxy’s traps are themselves a mechanism for intercepting the exact operations that well-known symbols expose a hook into, just at a broader scale than one property at a time.

Check yourself

  1. 01Two files both call `Symbol('id')`. Are the two resulting symbols equal to each other?

    No. The string passed to `Symbol()` is only a description for debugging — it has no effect on equality. Every call to `Symbol()` returns a brand-new, unique value, so `Symbol('id') === Symbol('id')` is `false` even with identical descriptions.

  2. 02Why would you use a symbol instead of a string as an object's property key?

    Mainly to guarantee the key can't collide with any other key — your own or someone else's — since no two symbols are ever equal. It's also a way to add a property that stays out of `for...in`, `Object.keys`, and `JSON.stringify`, which is useful for metadata that isn't meant to be "real" data on the object.

  3. 03What is a well-known symbol, and what does defining a method at `obj[Symbol.iterator]` actually do?

    A well-known symbol is one of a fixed set of symbols the JavaScript engine itself holds references to, used as hooks into built-in behavior. Defining `obj[Symbol.iterator]` as a function that returns an iterator makes `obj` iterable — the engine calls that function whenever `obj` is used with `for...of`, the spread operator, or destructuring.

  4. 04What does `Symbol.for('key')` do differently from plain `Symbol('key')`, and when would that difference matter?

    `Symbol.for` checks a global, engine-wide symbol registry for that key first, and returns the existing symbol if one's already there, creating it only if not — so repeated calls with the same key always return the *same* symbol. Plain `Symbol()` always mints a new one, so two calls never match. Use `Symbol.for` when separate parts of a codebase (or even separate script contexts) need to agree on the same symbol without sharing a direct reference to it.

  5. 05Besides `Symbol.iterator`, name one other well-known symbol and what it lets you control?

    `Symbol.toPrimitive` lets you control what value an object produces when it's coerced to a primitive — for example what `+obj`, `` `${obj}` ``, or `obj + 1` actually evaluate to — by defining a function at that key that returns the primitive yourself instead of the engine falling back to its default `toString`/`valueOf` behavior.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark