Symbols
Symbols are unique, immutable primitive values. Use them as non-colliding object property keys or to implement well-known protocols like iterators.
Symbols are unique, immutable primitive values. Use them as non-colliding object property keys or to implement well-known protocols like iterators.
const id = Symbol("id");
const user = { [id]: 42, name: "Alice" };
user[id]; // 42 — key not enumerable in for...in
Symbol("id") === Symbol("id"); // false — always unique
// Well-known symbols
class Range {
*[Symbol.iterator]() { for (let i = this.start; i <= this.end; i++) yield i; }
}
Symbol keys do not appear in JSON.stringify() or Object.keys(), useful for metadata.
More in JavaScript