# Symbols & Well-Known Symbols

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

Canonical: https://www.internhack.in/learn/interview/javascript-interview/js-symbols
Last updated: 2026-11-28

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

- `Symbol('description')` creates a brand new, unique Symbol. The description is only a debugging label, readable through `sym.description`.
- `Symbol.for('key')` looks up a **global registry** shared across every realm in the page, including iframes. The same key always returns the same Symbol. `Symbol.keyFor(sym)` returns the key for registered Symbols.
- `new Symbol()` throws a `TypeError`; Symbols are primitives, not constructors.
- `typeof sym` is `"symbol"`.

### 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

| Symbol | Used by | What it customises |
| --- | --- | --- |
| `Symbol.iterator` | `for...of`, spread, destructuring, `Array.from` | How the object is iterated |
| `Symbol.asyncIterator` | `for await...of` | Async iteration |
| `Symbol.toPrimitive` | `+obj`, \`` `${obj}` ``, `obj == x\` | Conversion to number, string or default |
| `Symbol.toStringTag` | `Object.prototype.toString` | The `[object Tag]` label |
| `Symbol.hasInstance` | `instanceof` | Whether a value counts as an instance |
| `Symbol.species` | `map`, `filter` on subclasses | Constructor 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

- Symbols are not implicitly converted to strings: `'id: ' + sym` throws a `TypeError`. Use `String(sym)` or `sym.description`.
- Symbols cannot be serialised with JSON, so they never cross the network.
- Since ES2023, non-registered Symbols can be used as `WeakMap` keys, but registered ones from `Symbol.for` cannot because they never get garbage collected.

**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

- Every Symbol() call returns a unique primitive; Symbol.for(key) returns a shared registered one.
- Symbol keys are skipped by Object.keys, for...in and JSON.stringify but visible via Object.getOwnPropertySymbols and Reflect.ownKeys.
- Symbols prevent name collisions; they are not a privacy mechanism.
- Well-known Symbols such as Symbol.iterator and Symbol.toPrimitive hook objects into language features.
- Symbols never convert to strings implicitly; use String(sym) or sym.description.

## Common follow-up questions

- How would you make a custom class iterable with for...of?
- What is the difference between Symbol() and Symbol.for()?
- How do Symbol properties compare to #private class fields?
- What does Symbol.asyncIterator enable?
- Why can registered Symbols not be used as WeakMap keys?

## Interview tips

- Correct the common misconception that Symbols make properties private; showing getOwnPropertySymbols proves you know the details.
- Have Symbol.iterator ready as your go-to well-known Symbol example.
- Mention a real use, such as library metadata keys, so the answer is not purely theoretical.

## Concepts covered

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

Previous: [Callback Hell & Async Patterns](https://www.internhack.in/learn/interview/javascript-interview/js-callback-patterns) · Next: [Proxy and Reflect API](https://www.internhack.in/learn/interview/javascript-interview/js-proxy-reflect) · [All of JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)

## More JavaScript Interview questions

- [WeakMap and WeakSet](https://www.internhack.in/learn/interview/javascript-interview/js-weakmap-weakset)
- [Generator Functions](https://www.internhack.in/learn/interview/javascript-interview/js-generators)
- [Optional Chaining and Nullish Coalescing](https://www.internhack.in/learn/interview/javascript-interview/js-optional-chaining-nullish)
- [Currying and Function Composition](https://www.internhack.in/learn/interview/javascript-interview/js-currying-composition)
- [Memoization](https://www.internhack.in/learn/interview/javascript-interview/js-memoization)
- [Property Descriptors and Object.defineProperty](https://www.internhack.in/learn/interview/javascript-interview/js-property-descriptors)

## Related

- [Learn](https://www.internhack.in/learn)
- [Interview Prep](https://www.internhack.in/learn/interview)
- [JavaScript Interview](https://www.internhack.in/learn/interview/javascript-interview)
