Sub topic 6
Well-Known Symbols: Hooks into the Language
Earlier chapters showed how to create your own symbols and use them as property keys. This chapter covers a set of symbols that you do not create. The language defines them, and its built-in operations look for them on your objects. When you put a method under one of these keys, you change how syntax such as for...of, instanceof, +, or String.prototype.replace treats that object.
This chapter assumes you know JavaScript primitives and typeof, objects with computed property names, ES6 classes (including static and getters), and for...of with spread syntax. It also assumes you have read the earlier chapters on symbol keys, reflection, and the global registry.
The goal here is the general model: what well-known symbols are, how the engine uses them, and which ones exist. Several of them get their own chapters later (Symbol.iterator, Symbol.asyncIterator, Symbol.toPrimitive, Symbol.toStringTag, Symbol.hasInstance). This chapter covers the remaining ones in more detail.
What Makes a Symbol "Well-Known"
A well-known symbol is a symbol value that the ECMAScript specification creates before any of your code runs. Each one is stored as a static property of the Symbol function, such as Symbol.iterator. The specification refers to them with names like @@iterator, and you will see that notation in MDN and in error messages.
They have three properties that set them apart from symbols you create yourself:
- They are fixed. The properties on
Symbolcannot be written, enumerated, or reconfigured. - They are not in the global registry.
Symbol.keyForreturnsundefinedfor them, just as it does for anySymbol()value. - They are shared across realms. An iframe, a Node
vmcontext, or a worker has its ownArrayandObject, butSymbol.iteratoris the same value in all of them. That is why an array from an iframe still works withfor...ofin the parent page.
const desc = Object.getOwnPropertyDescriptor(Symbol, 'iterator');
console.log(desc.writable, desc.enumerable, desc.configurable); // false false false
console.log(typeof Symbol.iterator); // "symbol"
console.log(Symbol.iterator.description); // "Symbol.iterator"
console.log(Symbol.keyFor(Symbol.iterator)); // undefined (not registered)
Symbol.iterator = Symbol('fake'); // silently ignored in sloppy mode, TypeError in strict mode
console.log(Symbol.iterator.description); // "Symbol.iterator"How the Engine Uses Them: The Protocol Model
Every well-known symbol follows the same pattern. A built-in operation that wants to allow customization reads a property from the object using the symbol as the key. If it finds a value, it uses that value. Otherwise it falls back to its default behavior.
The read is an ordinary property lookup. So:
- The method can live on the object itself, on its prototype, or on a class as a
staticmember, depending on what the operation reads. - Getters work. Some built-ins, such as
Symbol.species, are defined as getters. - The lookup happens each time the operation runs, not once when the object is created. Adding or deleting the property later changes behavior right away.
What happens without a value depends on the operation. Without Symbol.iterator, for...of has no default and throws TypeError: obj is not iterable. Without Symbol.hasInstance on a custom class, instanceof falls back to walking the prototype chain. Without Symbol.toStringTag, Object.prototype.toString reports "[object Object]".
The Full Set
The table lists the standard well-known symbols, what reads each one, and where this tutorial covers it.
| Symbol | Read by | Expected value | Covered |
|---|---|---|---|
| `Symbol.iterator` | `for...of`, spread, destructuring, `Array.from`, `Promise.all` | Method returning an iterator | Own chapter |
| `Symbol.asyncIterator` | `for await...of` | Method returning an async iterator | Own chapter |
| `Symbol.toPrimitive` | `+`, `==`, template literals, `Number()`, `String()` | Method taking a hint | Own chapter |
| `Symbol.toStringTag` | `Object.prototype.toString` | String | Own chapter |
| `Symbol.hasInstance` | `instanceof` (right-hand side) | Method returning a boolean | Own chapter |
| `Symbol.isConcatSpreadable` | `Array.prototype.concat` | Boolean flag | This chapter |
| `Symbol.species` | Array, Promise, RegExp, and typed array methods that create derived objects | Constructor (usually a static getter) | This chapter |
| `Symbol.match` | `String.prototype.match`, also "is this a regex?" checks | Method, or `false` to opt out | This chapter |
| `Symbol.matchAll` | `String.prototype.matchAll` | Method returning an iterator | This chapter |
| `Symbol.replace` | `String.prototype.replace`, `replaceAll` | Method | This chapter |
| `Symbol.search` | `String.prototype.search` | Method | This chapter |
| `Symbol.split` | `String.prototype.split` | Method | This chapter |
| `Symbol.unscopables` | `with` statements | Object of excluded names | This chapter |
Newer runtimes also include Symbol.dispose and Symbol.asyncDispose, which come from the explicit resource management proposal (using declarations). Check that your target environment supports them before you rely on them.
Symbol.isConcatSpreadable
concat flattens arguments that are arrays and appends anything else as a single element. Symbol.isConcatSpreadable overrides that choice in both directions.
const arrayLike = { length: 2, 0: 'a', 1: 'b', [Symbol.isConcatSpreadable]: true };
console.log([1].concat(arrayLike)); // [1, 'a', 'b']
const nested = [2, 3];
nested[Symbol.isConcatSpreadable] = false;
console.log([1].concat(nested)); // [1, [2, 3]]Set this flag on individual objects. If you set it on Array.prototype, every concat call in the program changes, including calls inside libraries you depend on.
Symbol.species
Methods such as map, filter, and slice build a new object. When the receiver is a subclass, the engine reads this.constructor[Symbol.species] to decide which constructor to use. By default, Array[Symbol.species] is a getter that returns this, so subclasses produce instances of themselves.
class TrackedArray extends Array {
static get [Symbol.species]() {
return Array; // derived results become plain arrays
}
}
const t = TrackedArray.from([1, 2, 3]);
const doubled = t.map(x => x * 2);
console.log(t instanceof TrackedArray); // true
console.log(doubled instanceof TrackedArray); // false
console.log(doubled instanceof Array); // trueThis is useful when your subclass constructor takes different arguments from Array, or when derived results should not carry the subclass's extra behavior. Symbol.species also has a history of security bugs and slows down built-in methods. TC39 has discussed restricting it, so avoid it in new designs unless you need it.
The String-Method Symbols
match, matchAll, replace, search, and split each check whether their first argument has the matching symbol method. If it does, they hand the work to that method. This is how RegExp plugs into string methods, and your own objects can do the same.
const censor = {
[Symbol.replace](str, replacement) {
return str.split('bad').join(replacement);
}
};
console.log('a bad, bad day'.replace(censor, '***')); // "a ***, *** day"Symbol.match has a second job. Methods such as startsWith, endsWith, and includes throw if you pass them a regular expression. They detect a regex by reading Symbol.match. If you set that property to false, the object is treated as an ordinary value and converted to a string.
const re = /foo/;
try {
'/foo/'.startsWith(re);
} catch (e) {
console.log(e instanceof TypeError); // true
}
re[Symbol.match] = false;
console.log('/foo/'.startsWith(re)); // true, compares against the string "/foo/"Symbol.unscopables
A with statement puts an object's properties into scope. When ES2015 added array methods such as keys and values, old code like with (arr) { values } would have started finding the method instead of an outer variable. Array.prototype[Symbol.unscopables] lists names that with should skip.
console.log(Array.prototype[Symbol.unscopables].values); // true
console.log(Array.prototype[Symbol.unscopables].flat); // truewith is not allowed in strict mode or in modules, so you will rarely write this symbol yourself. It mainly explains a backward-compatibility detail in the language.
Gotchas
You cannot invent new well-known symbols
Only the engine decides which keys it reads. Symbol.myHook is simply undefined. A typo produces the same problem, and it gives no error.
const obj = {
[Symbol.itrator]() {} // typo: Symbol.itrator is undefined
};
console.log(Object.keys(obj)); // ['undefined'], a string key
// [...obj]; // TypeError: obj is not iterableIf an object ends up with a string key named "undefined", look for a misspelled symbol name.
String names are not symbols
obj['Symbol.iterator'] creates an ordinary string-keyed property, and the engine ignores it. Always use the computed form [Symbol.iterator].
Static versus instance placement
Each operation reads the symbol from a specific object. instanceof reads Symbol.hasInstance from the right-hand operand, which is usually the class, so you define it as static. Symbol.species is read from the constructor, so it is also static. Symbol.iterator, Symbol.toPrimitive, and Symbol.toStringTag are read from the instance, so you define them as ordinary methods or getters, and they end up on the prototype. Putting a method in the wrong place has no effect and gives no error.
Global patches have global effects
Because the lookup is an ordinary property read, adding a well-known symbol to a built-in prototype changes that behavior for all code in the realm. Use these hooks on your own classes and objects.
Exercise
You add static *[Symbol.iterator]() { yield 1; } to a class Bag and then run [...new Bag()]. It throws "not iterable". Why, and how do you fix it?
Show answer
Spread reads Symbol.iterator from the value being spread, which is the instance. A static method lives on the constructor Bag, not on Bag.prototype, so instances never find it. Remove static so the generator becomes a prototype method. (As written, [...Bag] would work, because the class itself is iterable.)
Exercise
Predict the output: const x = { length: 1, 0: 'z' }; console.log([0].concat(x).length); x[Symbol.isConcatSpreadable] = true; console.log([0].concat(x).length);
Show answer
It prints 2, then 2. The first call appends the whole object as one element, giving [0, x]. The second call spreads its one indexed element, giving [0, 'z']. The lengths match, but the contents differ.
Exercise
Why does Symbol.keyFor(Symbol.iterator) return undefined even though Symbol.iterator is the same value in every realm?
Show answer
Symbol.keyFor only looks up symbols created with Symbol.for, which live in the global registry. Well-known symbols are shared across realms because the specification creates them that way, not because they are registered.