symbol

Contents

symbol#

Unique primitive identifiers. Use them for unforgeable object keys and for the well-known protocols (Symbol.iterator, Symbol.asyncIterator, Symbol.toPrimitive).

A symbol is unique even when two share the same description.

const a = Symbol("token");
const b = Symbol("token");
a === b;              // false

Symbol-keyed properties are invisible to for...in, Object.keys, and JSON.stringify; use Object.getOwnPropertySymbols to enumerate them.

const sym = Symbol("token");
const obj = {};
obj[sym] = "secret";
Object.keys(obj);                     // []
Object.getOwnPropertySymbols(obj);    // [Symbol(token)]

Implement a well-known protocol; here Symbol.iterator makes the class iterable.

class Counter {
  constructor() { this.n = 0; }
  *[Symbol.iterator]() {
    while (true) yield this.n++;
  }
}

Consume the iterator.

const c = new Counter();
for (const v of c) { if (v > 2) break; console.log(v); }

References#

  • object for the host of well-known protocol hooks.

  • OOP for class-side Symbol use.