Hint
Unique, non-string property keys β used for collision-free metadata and well-known protocols
A Symbol is a primitive that is guaranteed globally unique. Used mainly as object property keys to avoid name collisions.
const id = Symbol('id');
const id2 = Symbol('id');
id === id2; // false β always unique even with same description
const user = {};
user[id] = 42; // Symbol as property key
// Symbols are invisible to normal enumeration
Object.keys(user); // []
JSON.stringify(user); // '{}' β symbols excluded
Object.getOwnPropertySymbols(user); // [Symbol(id)] β explicit access
// Well-known Symbols β customize built-in behavior
class MyIterable {
[Symbol.iterator]() { // makes instances work in for...of
let n = 0;
return { next: () => n < 3
? { value: n++, done: false }
: { done: true } };
}
}
for (const v of new MyIterable()) console.log(v); // 0, 1, 2
// Other well-known Symbols:
// Symbol.toPrimitive β control type coercion
// Symbol.hasInstance β customize instanceof
// Symbol.toStringTag β customize Object.prototype.toString output