← Back to JavaScript, page 3

javascript-0047 · Hard senior

What are Symbols in JavaScript, and what are well-known symbols used for?

A Symbol is a unique, immutable primitive used as a property key that cannot collide with any other key. Symbol keys are skipped by for...in, Object.keys, and JSON.stringify. Well-known symbols such as Symbol.iterator, Symbol.toPrimitive, Symbol.toStringTag, and Symbol.hasInstance let an object customize how the language treats it.

Full answer

Symbol('label') creates a new value that is different from every other symbol, even one with the same description. The description is only for debugging. Symbols are primitives, but they cannot be converted to a string implicitly, so 'x' + symbol throws a TypeError. Use symbol.toString() or symbol.description.

As property keys, symbols avoid name collisions. A library can attach metadata to an object without clashing with the user's own keys. Symbol keys do not show up in for...in, Object.keys, Object.entries, or JSON.stringify. They are still not private. Object.getOwnPropertySymbols and Reflect.ownKeys list them. For true privacy, use #private fields.

Symbol.for('key') reads from a global registry shared across the whole program (and across realms such as iframes), returning the same symbol for the same key. This is for cases where separate pieces of code must agree on a key.

Well-known symbols are built-in keys that hook into language behavior:

  • Symbol.iterator makes an object iterable by for...of and spread.
  • Symbol.asyncIterator does the same for for await...of.
  • Symbol.toPrimitive controls conversion to a number, string, or default value.
  • Symbol.toStringTag changes the text in Object.prototype.toString output.
  • Symbol.hasInstance customizes instanceof.

These make symbols the entry point for much of JavaScript's metaprogramming.

javascript
const idA = Symbol('id');
const idB = Symbol('id');
console.log(idA === idB, idA.description, idA.toString());
console.log(Symbol.for('app.id') === Symbol.for('app.id'), Symbol.keyFor(Symbol.for('app.id')));

try {
  console.log('id: ' + idA);
} catch (error) {
  console.log('implicit string conversion:', error.name);
}

const user = { name: 'Tia', [idA]: 'hidden-key-value' };
console.log(Object.keys(user), JSON.stringify(user));
console.log(Object.getOwnPropertySymbols(user).length, Reflect.ownKeys(user));

class Money {
  constructor(amount) {
    this.amount = amount;
  }
  [Symbol.toPrimitive](hint) {
    return hint === 'string' ? `Rs ${this.amount}` : this.amount;
  }
  get [Symbol.toStringTag]() {
    return 'Money';
  }
}
const price = new Money(250);
console.log(`${price}`, price + 50, price * 2);
console.log(Object.prototype.toString.call(price));

class EvenNumber {
  static [Symbol.hasInstance](value) {
    return Number.isInteger(value) && value % 2 === 0;
  }
}
console.log(4 instanceof EvenNumber, 5 instanceof EvenNumber);

const range = {
  start: 1,
  end: 3,
  *[Symbol.iterator]() {
    for (let n = this.start; n <= this.end; n++) yield n;
  },
};
console.log([...range]);

Run with Node.js v24.22.1 as js-47.js; two runs gave identical output. Output: false id Symbol(id) true app.id implicit string conversion: TypeError [ 'name' ] {"name":"Tia"} 1 [ 'name', Symbol(id) ] Rs 250 300 500 [object Money] true false [ 1, 2, 3 ]

Key points

  • Every symbol is unique; the description is for debugging only.
  • Symbols cannot be implicitly converted to strings.
  • Symbol keys are hidden from for...in, Object.keys, and JSON but not private.
  • Symbol.for shares symbols through a global registry.
  • Well-known symbols (iterator, toPrimitive, toStringTag, hasInstance) customize language behavior.

Common mistakes

  • Treating symbol keys as private. Reflect.ownKeys reveals them.
  • Concatenating a symbol with a string and getting a TypeError.
  • Expecting JSON.stringify to include symbol-keyed properties.
  • Using Symbol.for for keys that should be unique to one module.

Follow-ups

  • How do private class fields differ from symbol keys?
  • How would you make a custom class work with for await...of?
  • What does the hint argument to Symbol.toPrimitive contain, and when is it default?

Tips

  • Lead with uniqueness and collision avoidance; then add the well-known symbols as the "hooks".
  • Say symbols are hidden but not private. It is the most common wrong claim.
  • Give two examples of well-known symbols you have used, with one line each.