Glossary / Well-known symbols
Well-known Symbols
Well-known Symbols are built-in Symbol values that expose language protocols. By defining a property with one of these keys, an object can customize how JavaScript treats it for iteration, primitive conversion, instanceof, string matching, and other operations. They are public hooks with specified contracts, not private magic methods.
Important protocols
Symbol.iterator: supplies a synchronous iterator forfor...of, spread, and iterable-consuming APIs.Symbol.asyncIterator: supplies an async iterator forfor await...of.Symbol.toPrimitive: controls conversion to a primitive for string/number/default hints.Symbol.hasInstance: customizes the right-hand side behavior ofinstanceof.Symbol.toStringTag: influences the tag returned byObject.prototype.toString.Symbol.match,replace,search,split: let objects customize corresponding String operations.
const countdown = {
*[Symbol.iterator]() {
yield 3; yield 2; yield 1;
},
};
[...countdown]; // [3, 2, 1]
A protocol implementation must honor its full semantics. An iterator must return iterator-result objects; an async iterator must coordinate Promise results and cleanup; a conversion hook should return an allowed primitive. Partial or inconsistent implementations can break generic consumers. Check browser/runtime compatibility before relying on newer protocols.
Design guidance
Implement well-known Symbols when your abstraction should integrate naturally with language syntax or standard APIs. Otherwise, explicit methods may be clearer. Do not monkey-patch built-in prototypes to add protocol behavior globally.
Interview questions
- Which Symbol makes an object iterable?
Symbol.iterator. - Which hook customizes
instanceof?Symbol.hasInstance. - What does Symbol.toPrimitive control? How an object converts to a primitive with a given hint.
- Are well-known Symbols private? No; they are public protocol keys.