Skip to content
  • Symbols · JavaScript

Symbols

LearnViaNotes @learnvianotes· 1 min read

A symbol is a unique, immutable primitive used as a property key that can never collide with any other key — and the gateway to customising built-in behaviour.

Creating symbols

JavaScript
const id1 = Symbol("id");
const id2 = Symbol("id");
console.log(id1 === id2, typeof id1, id1.description, id1.toString());

const user = { name: "Asha", [id1]: 123 };
console.log(user[id1], Object.keys(user), JSON.stringify(user));
console.log(Object.getOwnPropertySymbols(user), Reflect.ownKeys(user));

const shared = Symbol.for("app.token");      // global registry
console.log(shared === Symbol.for("app.token"), Symbol.keyFor(shared));
Output
false symbol id Symbol(id)
123 [ 'name' ] {"name":"Asha"}
[ Symbol(id) ] [ 'name', Symbol(id) ]
true app.token

Well-known symbols

SymbolCustomises
Symbol.iteratorfor…of, spread, destructuring
Symbol.asyncIteratorfor await…of
Symbol.toPrimitiveConversion to number/string
Symbol.toStringTagObject.prototype.toString output
Symbol.hasInstanceinstanceof
Symbol.dispose / asyncDisposeusing declarations (explicit resource management)
JavaScript
class Temperature {
  constructor(c) { this.c = c; }
  get [Symbol.toStringTag]() { return "Temperature"; }
  [Symbol.toPrimitive](hint) { return hint === "string" ? `${this.c}°C` : this.c; }
}
const t = new Temperature(21);
console.log(Object.prototype.toString.call(t), `${t}`, t + 1);

class Even {
  static [Symbol.hasInstance](n) { return Number.isInteger(n) && n % 2 === 0; }
}
console.log(4 instanceof Even, 3 instanceof Even);
Output
[object Temperature] 21°C 22
true false

What are Symbols used for?

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report