Well-known symbols are static properties of Symbol (written @@iterator in older spec text) that the engine consults during an operation. A method stored under one of these keys customizes that operation for your objects.
| Symbol | Consulted by |
|---|---|
| iterator, asyncIterator | for...of, for await...of (Iterables and Iterators) |
| match, matchAll, replace, search, split | Same-named string methods (Regular Expressions) |
| hasInstance | instanceof |
| toPrimitive, toStringTag | Type conversion, Object.prototype.toString() |
| species | map(), then()... (avoid: may be removed) |
| isConcatSpreadable, unscopables | concat(), with statements |
| dispose, asyncDispose | using, await using (ES2027) |
class Celsius {
constructor(deg) { this.deg = deg; }
[Symbol.toPrimitive](hint) { return hint === 'string' ? `${this.deg}°C` : this.deg; }
get [Symbol.toStringTag]() { return 'Celsius'; }
}
const t = new Celsius(21);
console.log(`${t}`, t + 1, Object.prototype.toString.call(t));21°C 22 [object Celsius]