Sub topic 6
Well-Known Symbols: Hooks into the Language
This chapter assumes you know how to create symbols, use them as computed property keys, and look them up with Symbol.for. It also assumes you are comfortable with ES6 classes and for...of.
So far you have created your own symbols. JavaScript also ships with a fixed set of symbols that it defines itself. These are the well-known symbols. They are stored as static properties on the Symbol function, such as Symbol.iterator and Symbol.toPrimitive. The language engine looks for them when it runs certain built-in operations.
The working model
Many language operations follow the same steps. Before falling back to its default behavior, the operation checks the object for a method stored under a particular well-known symbol. If it finds that method, it calls it. This gives you a hook: you change how the language treats your object by defining a method under the right symbol key.
Symbols work well for these hooks because they cannot collide with existing string keys. A class that already has a method named iterator or toPrimitive keeps working. The engine only looks at the symbol key, never the string key.
The main well-known symbols
| Symbol | Consulted by | Covered in |
|---|---|---|
| `Symbol.iterator` | `for...of`, spread, destructuring, `Array.from` | Making Objects Iterable |
| `Symbol.asyncIterator` | `for await...of` | Async Iteration |
| `Symbol.toPrimitive` | Conversion to number or string, `+`, template literals | Controlling Coercion |
| `Symbol.toStringTag` | `Object.prototype.toString` | Custom Type Tags |
| `Symbol.hasInstance` | `instanceof` | Customizing instanceof |
| `Symbol.isConcatSpreadable` | `Array.prototype.concat` | This chapter |
| `Symbol.species` | Array and Promise methods that create derived objects | Not covered |
| `Symbol.match`, `Symbol.replace`, `Symbol.search`, `Symbol.split` | String methods that accept regex-like objects | Not covered |
| `Symbol.unscopables` | `with` statements | Not covered |
Built-ins already use them
Built-in objects already define these hooks. Arrays are iterable because Array.prototype has a method under Symbol.iterator:
console.log(typeof Symbol.iterator); // "symbol"
console.log(typeof [][Symbol.iterator]); // "function"
console.log(Array.prototype[Symbol.iterator] === Array.prototype.values); // true
// Well-known symbols are not in the global registry
console.log(Symbol.keyFor(Symbol.iterator)); // undefinedThe well-known symbols are shared across every realm, including iframes and workers in the same agent cluster. However, they are not registered, so Symbol.keyFor returns undefined for them.
A first hook: Symbol.isConcatSpreadable
concat normally flattens arrays one level and treats other objects as single items. Setting Symbol.isConcatSpreadable changes that:
const arrayLike = { length: 2, 0: 'a', 1: 'b' };
console.log(['x'].concat(arrayLike).length); // 2 (object added as one item)
arrayLike[Symbol.isConcatSpreadable] = true;
console.log(['x'].concat(arrayLike)); // ['x', 'a', 'b']
const nested = [1, 2];
nested[Symbol.isConcatSpreadable] = false;
console.log([0].concat(nested).length); // 2 (array kept whole)The same pattern applies to every well-known symbol. You define the key, and the built-in operation changes its behavior.
Common errors
- Using a string instead of the symbol.
obj['Symbol.iterator'] = ...creates an ordinary string-keyed property, and the engine ignores it. Use the computed key[Symbol.iterator]. - Putting the hook on the wrong object.
Symbol.hasInstanceis read from the right-hand side ofinstanceof, which is the class itself, so it must be astaticmethod. Most other hooks belong on instances or the prototype. - Returning the wrong type.
Symbol.toPrimitivemust return a primitive, or aTypeErroris thrown.Symbol.iteratormust return an iterator object, orfor...ofthrows. - Expecting the hook to be hidden. Symbol-keyed methods still appear in
Reflect.ownKeysandObject.getOwnPropertySymbols, like any symbol key.
Exercise
A teammate writes class Bag { 'Symbol.iterator'() { return [1, 2][Symbol.iterator](); } } and finds that [...new Bag()] throws a TypeError. Why, and what is the fix?
Show answer
The method name is the string "Symbol.iterator", so it is an ordinary string-keyed method. Spread looks up the actual symbol Symbol.iterator and finds nothing. Use a computed key: [Symbol.iterator]() { return [1, 2][Symbol.iterator](); }.
Exercise
What does Symbol.keyFor(Symbol.toStringTag) return, and why?
Show answer
It returns undefined. Well-known symbols are shared across realms, but they are not entries in the global symbol registry. Symbol.keyFor only returns keys for symbols created with Symbol.for.