Well-known symbols and language hooks
Quick answer
Well-known symbols are predefined keys used by language and built-in protocols. A method stored under such a key can be called implicitly by an operation.
How it works
Symbol.iterator selects synchronous iteration; Symbol.asyncIterator selects asynchronous iteration. Conversion, branding, instance checks, construction and text matching have separate hooks. Symbol.isConcatSpreadable changes concat flattening; Symbol.unscopables affects legacy with lookup. Symbol.dispose and Symbol.asyncDispose identify cleanup methods for resource management; verify syntax support before using disposal statements. Hooks do not run just because a property exists: a consuming operation must consult them.
console.log(Symbol.iterator===Symbol("Symbol.iterator"), typeof Symbol.iterator);Expected output in Node.js:
false symbolA fresh symbol is not a predefined key.
const a={0:"x",length:1,[Symbol.isConcatSpreadable]:true}; console.log(JSON.stringify(["start"].concat(a)));Expected output in Node.js:
["start","x"]concat consults the spreadability hook.
Common mistakes
Creating Symbol("Symbol.iterator") does not reproduce the predefined key. Avoid customizing protocols unless the behavior is documented and unsurprising.
Practice
List the operations that would consult iterator, toPrimitive and isConcatSpreadable hooks.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Well-known symbols and language hooks — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which key is consulted by ordinary for...of?
What happens merely when a disposal symbol method is defined?
Which operation uses Symbol.isConcatSpreadable?
What is the exact console output in Well-known symbols and language hooks example 1?
console.log(Symbol.iterator===Symbol("Symbol.iterator"), typeof Symbol.iterator);What is the exact console output in Well-known symbols and language hooks example 2?
const a={0:"x",length:1,[Symbol.isConcatSpreadable]:true}; console.log(JSON.stringify(["start"].concat(a)));