Symbols in JavaScript
Introduction
A Symbol is a unique primitive value—ideal for property keys that should not collide with string keys like "name" or "id". Well-known symbols (Symbol.iterator, Symbol.toStringTag, etc.) let libraries hook into language behavior without polluting public APIs.
Prerequisites
Create Symbols
javascript
// Each Symbol() is unique
const a = Symbol("label");
const b = Symbol("label");
console.log(a === b);
console.log(typeof a);Optional description helps debugging only—not equality.
Symbol Keys on Objects
javascript
// Hidden-ish metadata key
const id = Symbol("id");
const user = {
name: "Ada",
[id]: 9001,
};
console.log(user.name);
console.log(user[id]);Symbol keys are skipped by Object.keys and for...in unless you use Object.getOwnPropertySymbols.
Global Symbol Registry
javascript
// Same symbol across files/realms
const shared = Symbol.for("app.config");
const again = Symbol.for("app.config");
console.log(shared === again);
console.log(Symbol.keyFor(shared));Well-Known Symbols
javascript
Other examples: Symbol.toStringTag, Symbol.hasInstance.
Symbol.iterator on Built-ins
Arrays, strings, Map, and Set already implement it—custom objects opt in as above.
Mini Example: Plugin Hook Key
javascript
FAQ
Symbol vs string key?
Symbols avoid name clashes; strings are normal public fields.
JSON and Symbols?
JSON.stringify ignores symbol-keyed properties.
Can I coerce Symbol to string?
String(sym) works; implicit + concatenation throws.