JavaScriptMedium
What is Symbol?
Symbol is a primitive type whose values are always unique; symbols are mainly used as property keys that cannot collide with any other key, and well-known symbols let you customise how built-in language features treat your objects.
Creating symbols
Symbol("description"): a new, unique symbol every time. The description is only a label for debugging.Symbol.for("key"): a global registry symbol; the same key returns the same symbol everywhere, even across realms such as iframes.
Symbols as property keys
- Guaranteed not to clash with string keys or other libraries' keys.
- Hidden from
for...in,Object.keys, andJSON.stringify. They are not private, though:Object.getOwnPropertySymbolsandReflect.ownKeysreveal them. (For real privacy, use#privatefields.)
Well-known symbols
Symbol.iterator: makes an object iterable withfor...ofand spread.Symbol.asyncIterator: forfor await...of.Symbol.toPrimitive: control conversion to numbers and strings.Symbol.toStringTag: customiseObject.prototype.toStringoutput.Symbol.hasInstance: customiseinstanceof.Symbol.dispose/Symbol.asyncDispose: used by theusingdeclarations from the explicit resource management proposal, which is rolling out in engines.
Use cases
Library metadata that will not collide with user properties, enum-like constants that cannot be confused with strings, and implementing language protocols like iteration.
Code example
js
1const id1 = Symbol("id");2const id2 = Symbol("id");3console.log(id1 === id2, typeof id1, id1.description); // false "symbol" "id"4console.log(Symbol.for("app.version") === Symbol.for("app.version")); // true (global registry)56// Collision-free, hidden-from-JSON keys7const META = Symbol("meta");8const user = { name: "Ada", [META]: { fetchedAt: 1700000000 } };9console.log(Object.keys(user), JSON.stringify(user)); // ["name"] {"name":"Ada"}10console.log(user[META].fetchedAt); // 170000000011console.log(Object.getOwnPropertySymbols(user).length); // 1 - discoverable, so not truly private1213// Enum-like constants that can't be mistaken for strings14const Status = Object.freeze({ Active: Symbol("active"), Banned: Symbol("banned") });15const check = (s) => (s === Status.Active ? "welcome" : "denied");16console.log(check(Status.Active), check("active")); // welcome denied1718// Well-known symbols customise built-in behaviour19class Range {20 constructor(from, to) {21 Object.assign(this, { from, to });22 }23 *[Symbol.iterator]() {24 for (let i = this.from; i <= this.to; i++) yield i;25 }26 get [Symbol.toStringTag]() {27 return "Range";28 }29}30const r = new Range(1, 4);31console.log([...r], Object.prototype.toString.call(r)); // [1, 2, 3, 4] "[object Range]"
Practice this question
Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the JavaScript set.