Symbols

Updated · 6 min read
mediumES2026javascriptsymbolwell-known-symbolsiterator

A symbol is a primitive value that is guaranteed to be unique: every call to Symbol() creates a new value that is equal to no other. Symbols are used as property keys that can't collide with any other key, whether yours, a library's, or one added to the language in the future. The language itself uses a set of well-known symbols such as Symbol.iterator to let your objects plug into built-in behavior like for...of. This lesson is optional on a first pass; you'll meet symbols again with iterators and classes.

In One Minute

  • Symbol("description") creates a unique value; the description is only a label for debugging.
  • Use symbols as object keys with brackets: obj[key] = value, { [key]: value }.
  • Symbol keys are skipped by for...in, Object.keys and JSON.stringify, but they are not private.
  • Symbol.for("name") returns a shared symbol from a global registry, the same one everywhere.
  • Well-known symbols (Symbol.iterator, Symbol.toPrimitive, Symbol.toStringTag...) customize how objects behave with built-in operations.

Creating Symbols

create.js▶ Try it
const id1 = Symbol("id");
const id2 = Symbol("id");
 
console.log(typeof id1);
console.log(id1 === id2);
console.log(id1.description);
console.log(id1.toString());
Output
symbol
false
id
Symbol(id)

Two symbols with the same description are still different values. The description exists only to make symbols readable in logs and debuggers. Symbols can't be created with new (new Symbol() throws), and they can't be implicitly converted to strings: "key: " + id1 throws a TypeError. Use String(id1) or id1.description.

Symbols as Property Keys

A symbol key can't collide with a string key, or with another symbol:

keys.js▶ Try it
const internalId = Symbol("internalId");
 
const student = {
  name: "Navika",
  id: "S-001",
  [internalId]: 4471,
};
 
console.log(student.id, student[internalId]);
console.log(Object.keys(student));
console.log(JSON.stringify(student));
 
for (const key in student) console.log("for...in:", key);
console.log(Object.getOwnPropertySymbols(student));
Output
S-001 4471
['name', 'id']
{"name":"Navika","id":"S-001"}
for...in: name
for...in: id
[Symbol(internalId)]

Explanation: the symbol property sits alongside a string property named id without clashing. It is skipped by Object.keys, for...in and JSON.stringify, so it doesn't show up in ordinary loops or saved data. But Object.getOwnPropertySymbols (and Reflect.ownKeys) still find it.

Why Use Symbol Keys

The main reason is avoiding collisions when you add data to objects you don't fully control. If a library tagged objects with a string property like _meta, it could clash with your own _meta or another library's. A symbol key can't clash with anything:

tagging.js▶ Try it
const RECEIPT_SENT = Symbol("receiptSent");
 
function markSent(payment) {
  payment[RECEIPT_SENT] = true;
}
 
const payment = { amount: 120, receiptSent: "custom field from the server" };
markSent(payment);
console.log(payment.receiptSent);
console.log(payment[RECEIPT_SENT]);
Output
custom field from the server
true

The Global Symbol Registry

Symbol() always creates a new, unique symbol. Symbol.for(key) instead looks up a global registry: it returns the existing symbol for that key, or creates and registers one. The same key gives the same symbol anywhere in the program, even across modules, iframes or workers:

registry.js▶ Try it
const a = Symbol.for("feeTracker.version");
const b = Symbol.for("feeTracker.version");
const c = Symbol("feeTracker.version");
 
console.log(a === b);
console.log(a === c);
console.log(Symbol.keyFor(a));
console.log(Symbol.keyFor(c));
Output
true
false
feeTracker.version
undefined

Use registered symbols when separate parts of a system must agree on a key without sharing a variable. Give the key a namespace (like "feeTracker.version") so it doesn't clash with other code using the registry.

Well-Known Symbols

The language defines built-in symbols, stored as properties of Symbol, that let your objects customize built-in behavior. They are called well-known symbols:

SymbolCustomizes
Symbol.iteratorHow for...of, spread and destructuring iterate the object
Symbol.asyncIteratorHow for await...of iterates it
Symbol.toPrimitiveHow it converts to a primitive (see the type coercion lesson)
Symbol.toStringTagThe tag in Object.prototype.toString ("[object Tag]")
Symbol.hasInstanceHow instanceof behaves
Symbol.dispose, Symbol.asyncDisposeCleanup with using (memory lesson)

Making an Object Iterable

The most useful one: give an object a [Symbol.iterator] method, and for...of and spread work on it. A generator function (function*, covered in the generators lesson) is the easiest way to write one:

iterable.js▶ Try it
const feeSchedule = {
  base: 400,
  step: 15,
  grades: [9, 10, 11, 12],
  *[Symbol.iterator]() {
    for (const grade of this.grades) {
      yield { grade, fee: this.base + (grade - 9) * this.step };
    }
  },
};
 
for (const { grade, fee } of feeSchedule) {
  console.log(`Grade ${grade}: $${fee}`);
}
console.log([...feeSchedule].length);
Output
Grade 9: $400
Grade 10: $415
Grade 11: $430
Grade 12: $445
4

A Custom Type Tag

tag.js▶ Try it
class FeeAccount {
  get [Symbol.toStringTag]() {
    return "FeeAccount";
  }
}
 
console.log(Object.prototype.toString.call(new FeeAccount()));
console.log(String(new FeeAccount()));
Output
[object FeeAccount]
[object FeeAccount]

In Practice

The Fee Tracker attaches cached totals to payment lists with a symbol key, so the cache never appears when the list is saved as JSON or looped over:

cache.js▶ Try it
const CACHED_TOTAL = Symbol("cachedTotal");
 
function total(list) {
  if (list[CACHED_TOTAL] === undefined) {
    list[CACHED_TOTAL] = list.reduce((sum, p) => sum + p.amount, 0);
  }
  return list[CACHED_TOTAL];
}
 
const payments = [{ amount: 120 }, { amount: 85 }];
console.log(total(payments));
console.log(JSON.stringify(payments));
console.log(Object.keys(payments));
Output
205
[{"amount":120},{"amount":85}]
['0', '1']

Common Mistakes

Using dot notation with a symbol. obj.mySymbol reads a string property named "mySymbol". Use obj[mySymbol].

Expecting symbol keys to be private. Object.getOwnPropertySymbols reveals them.

Joining a symbol into a string with +. It throws TypeError: Cannot convert a Symbol value to a string. Use String(sym) or sym.description.

Expecting Symbol("x") === Symbol("x"). Never true. Use Symbol.for("x") when you need the same symbol twice.

Practice

Challenge: Make a range object with from and to properties iterable with Symbol.iterator, so [...range] gives every whole number from from to to.

Show solution
range.js▶ Try it
const range = {
  from: 3,
  to: 7,
  *[Symbol.iterator]() {
    for (let n = this.from; n <= this.to; n++) yield n;
  },
};
 
console.log([...range]);
console.log(Math.max(...range));
Output
[3, 4, 5, 6, 7]
7

Quick check: Symbols

3 questions
1What is Symbol("a") === Symbol("a")?
2Which of these lists symbol keys?
3What does adding a [Symbol.iterator] method to an object enable?

Key Takeaways

TaskCode
Createconst s = Symbol("label")
Use as a keyobj[s] = 1, { [s]: 1 }
Shared symbolSymbol.for("app.key")
List symbol keysObject.getOwnPropertySymbols(obj)
Make iterable*[Symbol.iterator]() { yield ... }

Was this tutorial helpful?

Lesson 54 of 139