Symbols & Well-Known Symbols

Difficulty: Intermediate

Question

What is a Symbol in JavaScript? How are Symbols used as property keys, and what are well-known Symbols?

Answer

A Symbol is a primitive type (added in ES2015) whose every value is unique: Symbol('id') !== Symbol('id'). Symbols are mainly used as property keys that cannot clash with string keys, and as well-known Symbols like Symbol.iterator that let your objects plug into built-in language behaviour such as for...of, type conversion and instanceof.

Creating Symbols

Symbols as property keys

Symbol-keyed properties are skipped by for...in, Object.keys, Object.entries and JSON.stringify. They are still reachable through Object.getOwnPropertySymbols(obj) and Reflect.ownKeys(obj), and Object.assign and object spread do copy them. So Symbols give you collision-free keys, not private ones. For real privacy use class #private fields or a WeakMap.

This is useful when you attach metadata to objects you do not own. A library can tag objects with obj[kTracked] = true without any risk of colliding with a user property called tracked. Node.js uses this pattern internally, for example util.inspect.custom is a registered Symbol (Symbol.for('nodejs.util.inspect.custom')).

Well-known Symbols

SymbolUsed byWhat it customises
Symbol.iteratorfor...of, spread, destructuring, Array.fromHow the object is iterated
Symbol.asyncIteratorfor await...ofAsync iteration
Symbol.toPrimitive+obj, ` ${obj} , obj == x`Conversion to number, string or default
Symbol.toStringTagObject.prototype.toStringThe [object Tag] label
Symbol.hasInstanceinstanceofWhether a value counts as an instance
Symbol.speciesmap, filter on subclassesConstructor used for derived objects

Newer additions include Symbol.dispose and Symbol.asyncDispose for the explicit resource management proposal (using declarations), which shipped in recent V8 and TypeScript versions.

Gotchas

Symbol keys stay out of listings. Toggle the Symbol property and try Object.keys or JSON.stringify under Tweak.
  1. Unique keys: Symbol("secret") never collides with any string key.
  2. Invisible to keys and JSON: Object.keys, for...in and JSON.stringify skip symbol keys.
  3. Still accessible: obj[secret] reads it; Reflect.ownKeys lists it.

Code examples

Symbol basics and visibility

const id = Symbol('id');
const user = { name: 'Asha', [id]: 101 };

console.log(Symbol('id') === Symbol('id'));    // unique every time
console.log(typeof id, id.description);
console.log(user[id]);
console.log(Object.keys(user));                 // Symbol keys are skipped
console.log(JSON.stringify(user));
console.log(Object.getOwnPropertySymbols(user)); // but not hidden
console.log({ ...user }[id]);                   // spread copies them

// Global registry
console.log(Symbol.for('app.id') === Symbol.for('app.id'));
console.log(Symbol.keyFor(Symbol.for('app.id')));

try {
  console.log('key: ' + id);
} catch (e) {
  console.log(e.constructor.name);
}

Symbol keys stay out of Object.keys and JSON but are still discoverable, so they prevent collisions rather than guarantee privacy. Symbol.for shares one Symbol per key through the global registry.

Custom Iterable with Symbol.iterator

class Range {
  constructor(start, end) {
    this.start = start;
    this.end = end;
  }

  [Symbol.iterator]() {
    let current = this.start;
    const end = this.end;
    return {
      next() {
        return current <= end
          ? { value: current++, done: false }
          : { done: true };
      }
    };
  }
}

const range = new Range(1, 5);
console.log([...range]);

for (const n of range) {
  process.stdout.write(n + " ");
}

Symbol.iterator makes objects work with for...of loops and the spread operator.

Symbol.toPrimitive and Symbol.toStringTag

class Money {
  constructor(paise) { this.paise = paise; }

  [Symbol.toPrimitive](hint) {
    if (hint === 'number') return this.paise / 100;
    return `Rs ${(this.paise / 100).toFixed(2)}`; // 'string' and 'default'
  }

  get [Symbol.toStringTag]() { return 'Money'; }
}

const price = new Money(49900);
console.log(+price);                       // hint: number
console.log(`${price}`);                   // hint: string
console.log(Object.prototype.toString.call(price));

Symbol.toPrimitive receives a hint telling you which conversion the engine wants. Symbol.toStringTag changes the label used by Object.prototype.toString, which some type-checking utilities rely on.

Key points

Common follow-up questions

Interview tips

Concepts covered

Symbol, Symbol.for, Well-Known Symbols, Symbol.iterator, Symbol.toPrimitive

More JavaScript Interview questions