20. Symbols
Symbols are primitive values that are created via the factory function Symbol()
:
The parameter is optional and provides a description, which is mainly useful for debugging.
On one hand, symbols are like objects in that each value created by Symbol()
is unique and not compared by value:
On the other hand, they also behave like primitive values – they have to be categorized via typeof
and they can be property keys in objects:
20.1. Use cases for symbols
The main use cases for symbols are:
- Defining constants for the values of an enumerated type.
- Creating unique property keys.
20.1.1. Symbols: enum-style values
Let’s assume you want to create constants representing the colors red, orange, yellow, green, blue and violet. One simple way of doing so would be to use strings:
On the plus side, logging that constant produces helpful output. On the minus side, there is a risk of mistaking an unrelated value for a color, because two strings with the same content are considered equal:
We can fix that problem via a symbol:
Let’s use symbol-valued constants to implement a function:
const COLOR_RED = Symbol('Red');
const COLOR_ORANGE = Symbol('Orange');
const COLOR_YELLOW = Symbol('Yellow');
const COLOR_GREEN = Symbol('Green');
const COLOR_BLUE = Symbol('Blue');
const COLOR_VIOLET = Symbol('Violet');
function getComplement(color) {
switch (color) {
case COLOR_RED:
return COLOR_GREEN;
case COLOR_ORANGE:
return COLOR_BLUE;
case COLOR_YELLOW:
return COLOR_VIOLET;
case COLOR_GREEN:
return COLOR_RED;
case COLOR_BLUE:
return COLOR_ORANGE;
case COLOR_VIOLET:
return COLOR_YELLOW;
default:
throw new Exception('Unknown color: '+color);
}
}
assert.equal(getComplement(COLOR_YELLOW), COLOR_VIOLET);
Notably, this function throws an exception if you call it with 'Blue'
:
20.1.2. Symbols: unique property keys
The keys of properties (fields) in objects are used at two levels:
The program operates at a base level. Its keys reflect the problem domain.
Libraries and ECMAScript operate at a meta-level. For example,
.toString
is a meta-level property key:
The following code demonstrates the difference:
Properties .x
and .y
exist at the base level. They are the coordinates of the point encoded by point
and reflect the problem domain. Method .toString()
is a meta-level property. It tells JavaScript how to stringify this object.
The meta-level and the base level must never clash, which becomes harder when introducing new mechanisms later in the life of a programming language.
Symbols can be used as property keys and solve this problem: Each symbol is unique and never clashes with any string or any other symbol.
As an example, let’s assume we are writing a library that treats objects differently if they implement a special method. This is what defining a property key for such a method and implementing it for an object would look like:
This syntax is explained in more detail in the chapter on objects.
20.2. Publicly known symbols
Symbols that play special roles within ECMAScript are called publicly known symbols. Examples include:
Symbol.iterator
: makes an object iterable. It’s the key of a method that returns an iterator. Iteration is explained in its own chapter.Symbol.hasInstance
: customizes howinstanceof
works. It’s the key of a method to be implemented by the right-hand side of that operator. For example:
Symbol.toStringTag
: influences the default.toString()
method.
Note: It’s usually better to override .toString()
.
20.3. Converting symbols
What happens if we convert a symbol sym
to another primitive type? Tbl. 17 has the answers.
Convert to | Explicit conversion | Coercion (implicit conv.) |
---|---|---|
boolean | Boolean(sym) → OK | !sym → OK |
number | Number(sym) → TypeError | sym*2 → TypeError |
string | String(sym) → OK | ''+sym → TypeError |
sym.toString() → OK | → TypeError |
One key pitfall with symbols is how often exceptions are thrown when converting them to something else. What is the thinking behind that? First, conversion to number never makes sense and should be warned about. Second, converting a symbol to a string is indeed useful for diagnostic output. But it also makes sense to warn about accidentally turning a symbol into a string property key:
The downside is that the exceptions make working with symbols more complicated. You have to explicitly convert symbols when assembling strings via the plus operator:
20.4. Further reading
- For in-depth information on symbols (cross-realm symbols, all publicly known symbols, etc.), see “Exploring ES6”