Well-known symbols — Symbol.iterator, toPrimitive, toStringTag¶
Level: 301 · for anyone who has used Symbol.iterator and wants the rest
Stub — an outline, not a lesson. There is no runnable example behind this page yet, so nothing on it has been through the check that backs every other claim in this library. The questions below are what the finished page has to answer.
One line: Node lists 15 well-known symbols, each a hook the language calls on your objects: a static [Symbol.hasInstance] makes 2 instanceof Even answer true, and [Symbol.toStringTag] makes Object.prototype.toString report [object Array] for an object that is no array.
Keywords: Symbol.toStringTag, Symbol.hasInstance, Symbol.isConcatSpreadable, well-known symbols
What the finished page will answer¶
- Which 15 well-known symbols does Node list on
Symbol, and which two arrived withusing? - What do
2 instanceof Evenand3 instanceof Evenprint whenEvenhas a static[Symbol.hasInstance]? - How does
[Symbol.toStringTag]changeObject.prototype.toString, and why does that make"[object Array]"a weaker array test thanArray.isArray? - What does
[Symbol.isConcatSpreadable]change about[].concat(x)? - Which hint does
[Symbol.toPrimitive]receive for+obj,`${obj}`andobj + ""?
Examples it will need¶
-
well_known_symbols_list_js.js— each well-known symbol on Symbol, one per line -
well_known_symbols_hooks_js.js— one object with toStringTag, hasInstance, isConcatSpreadable and toPrimitive, and what each operator then answers
See also¶
- Symbols — what a symbol is, before the well-known ones
- ToPrimitive — the full story of Symbol.toPrimitive
- The iteration protocol — the full story of Symbol.iterator
instanceof— the lookup that Symbol.hasInstance replacesusingandSymbol.dispose— the newest well-known symbol, Symbol.dispose, at work- Rust: Implementing
Iterator↗ — the Rust counterpart of Symbol.iterator: the Iterator trait