[ ]and wrapped keys
Symbols are a new primitive type in ECMAScript 6. They are created via a factory function:
Every time you call the factory function, a new and unique symbol is created. The optional parameter is a descriptive string that is shown when printing the symbol (it has no other purpose):
Symbols are mainly used as unique property keys – a symbol never clashes with any other property key (symbol or string). For example, you can make an object iterable (usable via the
for-of loop and other language mechanisms), by using the symbol stored in
Symbol.iterator as the key of a method (more information on iterables is given in the chapter on iteration):
In line A, a symbol is used as the key of the method. This unique marker makes the object iterable and enables us to use the
In ECMAScript 5, you may have used strings to represent concepts such as colors. In ES6, you can use symbols and be sure that they are always unique:
Every time you call
Symbol('Red'), a new symbol is created. Therefore,
COLOR_RED can never be mistaken for another value. That would be different if it were the string
Coercing (implicitly converting) symbols to strings throws exceptions:
The only solution is to convert explicitly:
Forbidding coercion prevents some errors, but also makes working with symbols more complicated.
The following operations are aware of symbols as property keys:
The following operations ignore symbols as property keys:
ECMAScript 6 introduces a new primitive type: symbols. They are tokens that serve as unique IDs. You create symbols via the factory function
Symbol() (which is loosely similar to
String returning strings if called as a function):
Symbol() has an optional string-valued parameter that lets you give the newly created Symbol a description. That description is used when the symbol is converted to a string (via
Every symbol returned by
Symbol() is unique, every symbol has its own identity:
You can see that symbols are primitive if you apply the
typeof operator to one of them – it will return a new symbol-specific result:
Symbols can be used as property keys:
Classes and object literals have a feature called computed property keys: You can specify the key of a property via an expression, by putting it in square brackets. In the following object literal, we use a computed property key to make the value of
MY_KEY the key of a property.
A method definition can also have a computed key:
Given that there is now a new kind of value that can become the key of a property, the following terminology is used for ECMAScript 6:
Let’s examine the APIs for enumerating own property keys by first creating an object.
Object.getOwnPropertyNames() ignores symbol-valued property keys:
Object.getOwnPropertySymbols() ignores string-valued property keys:
Reflect.ownKeys() considers all kinds of keys:
Object.keys() only considers enumerable property keys that are strings:
Object.keys clashes with the new terminology (only string keys are listed).
Object.getEnumerableOwnPropertyNames would be a better choice now.
In ECMAScript 5, one often represents concepts (think enum constants) via strings. For example:
However, strings are not as unique as we’d like them to be. To see why, let’s look at the following function.
It is noteworthy that you can use arbitrary expressions as
switch cases, you are not limited in any way. For example:
We use the flexibility that
switch offers us and refer to the colors via our constants (
COLOR_RED etc.) instead of hard-coding them (
Interestingly, even though we do so, there can still be mix-ups. For example, someone may define a constant for a mood:
Now the value of
COLOR_BLUE is not unique anymore and
MOOD_BLUE can be mistaken for it. If you use it as a parameter for
getComplement(), it returns
'Orange' where it should throw an exception.
Let’s use symbols to fix this example. Now we can also use the ES6 feature
const, which lets us declare actual constants (you can’t change what value is bound to a constant, but the value itself may be mutable).
Each value returned by
Symbol is unique, which is why no other value can be mistaken for
BLUE now. Intriguingly, the code of
getComplement() doesn’t change at all if we use symbols instead of strings, which shows how similar they are.
Being able to create properties whose keys never clash with other keys is useful in two situations:
For usability’s sake, public properties usually have string keys. But for private properties with string keys, accidental name clashes can become a problem. Therefore, symbols are a good choice. For example, in the following code, symbols are used for the private properties
Note that symbols only protect you from name clashes, not from unauthorized access, because you can find out all own property keys – including symbols – of an object via
Reflect.ownKeys(). If you want protection there, as well, you can use one of the approaches listed in Sect. “Private data for classes”.
Symbols having unique identities makes them ideal as keys of public properties that exist on a different level than “normal” property keys, because meta-level keys and normal keys must not clash. One example of meta-level properties are methods that objects can implement to customize how they are treated by a library. Using symbol keys protects the library from mistaking normal methods as customization methods.
ES6 Iterability is one such customization. An object is iterable if it has a method whose key is the symbol (stored in)
Symbol.iterator. In the following code,
obj is iterable.
The iterability of
obj enables you to use the
Array.prototype.values()was created, it broke existing code where
withwas used with an Array and shadowed a variable
valuesin an outer scope (bug report 1, bug report 2). Therefore, a mechanism was introduced to hide properties from
String.prototype.containsclashed with a method added by MooTools and had to be renamed to
Array.prototype.containsalso clashed with a method added by MooTools and had to be renamed to
In contrast, adding iterability to an object via the property key
Symbol.iterator can’t cause problems, because that key doesn’t clash with anything.
The following table shows what happens if you explicitly or implicitly convert symbols to other primitive types:
|Conversion to||Explicit conversion||Coercion (implicit conversion)|
Coercion to string being forbidden can easily trip you up:
To fix these problems, you need an explicit conversion to string:
Coercion (implicit conversion) is often forbidden for symbols. This section explains why.
Coercion to boolean is always allowed, mainly to enable truthiness checks in
if statements and other locations:
Symbols are special property keys, which is why you want to avoid accidentally converting them to strings, which are a different kind of property keys. This could happen if you use the addition operator to compute the name of a property:
That’s why a
TypeError is thrown if
value is a symbol.
You also don’t want to accidentally turn symbols into Array indices. The following is code where that could happen if
value is a symbol:
That’s why the addition operator throws an error in this case.
To explicitly convert a symbol to boolean, you call
Boolean(), which returns
true for symbols:
Boolean() computes its result via the internal operation
ToBoolean(), which returns
true for symbols and other truthy values.
Coercion also uses
To explicitly convert a symbol to number, you call
Number() computes its result via the internal operation
ToNumber(), which throws a
TypeError for symbols.
Coercion also uses
To explicitly convert a symbol to string, you call
If the parameter of
String() is a symbol then it handles the conversion to string itself and returns the string
Symbol() wrapped around the description that was provided when creating the symbol. If no description was given, the empty string is used:
toString() method returns the same string as
String(), but neither of these two operations calls the other one, they both call the same internal operation
Coercion is handled via the internal operation
ToString(), which throws a
TypeError for symbols. One method that coerces its parameter to string is
The addition operator works as follows:
ToString()), concatenate them and return the result.
Coercion to either string or number throws an exception, which means that you can’t (directly) use the addition operator for symbols:
While all other primitive values have literals, you need to create symbols by function-calling
Symbol. Thus, there is a risk of accidentally invoking
Symbol as a constructor. That produces instances of
Symbol, which are not very useful. Therefore, an exception is thrown when you try to do that:
There is still a way to create wrapper objects, instances of
Object, called as a function, converts all values to objects, including symbols.
[ ]and wrapped keys
The square bracket operator
[ ] normally coerces its operand to string. There are now two exceptions: symbol wrapper objects are unwrapped and symbols are used as they are. Let’s use the following object to examine this phenomenon.
The square bracket operator unwraps wrapped symbols:
Like any other value not related to symbols, a wrapped string is converted to a string by the square bracket operator:
The operator for getting and setting properties uses the internal operation
ToPropertyKey(), which works as follows:
ToPrimitive()with the preferred type
[@@toPrimitive](), that method is used to convert it to a primitive value. Symbols have such a method, which returns the wrapped symbol.
toString()– if it returns a primitive value. Otherwise,
valueOf()is used – if it returns a primitive value. Otherwise, a
TypeErroris thrown. The preferred type
toString()is called first,
A code realm (short: realm) is a context in which pieces of code exist. It includes global variables, loaded modules and more. Even though code exists “inside” exactly one realm, it may have access to code in other realms. For example, each frame in a browser has its own realm. And execution can jump from one frame to another, as the following HTML demonstrates.
The problem is that each realm has its own global variables where each variable
Array points to a different object, even though they are all essentially the same object. Similarly, libraries and user code are loaded once per realm and each realm has a different version of the same object.
Objects are compared by identity, but booleans, numbers and strings are compared by value. Therefore, no matter in which realm a number 123 originated, it is indistinguishable from all other 123s. That is similar to the number literal
123 always producing the same value.
Symbols have individual identities and thus don’t travel across realms as smoothly as other primitive values. That is a problem for symbols such as
Symbol.iterator is the same value in each realm. If a library wants to provide cross-realm symbols, it has to rely on extra support, which comes in the form of the global symbol registry: This registry is global to all realms and maps strings to symbols. For each symbol, the library needs to come up with a string that is as unique as possible. To create the symbol, it doesn’t use
Symbol(), it asks the registry for the symbol that the string is mapped to. If the registry already has an entry for the string, the associated symbol is returned. Otherwise, entry and symbol are created first.
You ask the registry for a symbol via
Symbol.for() and retrieve the string associated with a symbol (its key) via
Cross-realm symbols, such as
The original plan was for symbols to support private properties (there would have been public and private symbols). But that feature was dropped, because using “get” and “set” (two meta-object protocol operations) for managing private data does not interact well with proxies:
These two goals are at odds. The chapter on classes explains your options for managing private data. Symbols is one of these options, but you don’t get the same amount of safety that you’d get from private symbols, because it’s possible to determine the symbols used as an object’s property keys, via
In some ways, symbols are like primitive values, in other ways, they are like objects:
What are symbols then – primitive values or objects? In the end, they were turned into primitives, for two reasons.
First, symbols are more like strings than like objects: They are a fundamental value of the language, they are immutable and they can be used as property keys. Symbols having unique identities doesn’t necessarily contradict them being like strings: UUID algorithms produce strings that are quasi-unique.
Symbols not having these abilities makes life easier for the specification and the implementations. The V8 team has also said that when it comes to property keys, it is easier to make a primitive type a special case than certain objects.
In contrast to strings, symbols are unique and prevent name clashes. That is nice to have for tokens such as colors, but it is essential for supporting meta-level methods such as the one whose key is
Symbol.iterator. Python uses the special name
There is one hypothetical alternative to symbols when it comes to clash-free property keys: using a naming convention. For example, strings with URLs (e.g.
'http://example.com/iterator'). But that would introduce a second category of property keys (versus “normal” property names that are usually valid identifiers and don’t contain colons, slashes, dots, etc.), which is basically what symbols are, anyway. Then we may just as well introduce a new kind of value.
No, they are not.
Ruby’s symbols are basically literals for creating values. Mentioning the same symbol twice produces the same value twice:
Symbol() is a factory for symbols – each value it returns is unique:
Well-known symbols are stored in properties whose names start with lowercase characters and are camel-cased. In a way, these properties are constants and it is customary for constants to have all-caps names (
Math.PI etc.). But the reasoning for their spelling is different: Well-known symbols are used instead of normal property keys, which is why their “names” follow the rules for property keys, not the rules for constants.
This section gives an overview of the ECMAScript 6 API for symbols.
Symbol(description?) : symbol
Creates a new symbol. The optional parameter
description allows you to give the symbol a description. The only way to access the description is to convert the symbol to a string (via
String()). The result of such a conversion is
Symbol is can’t be used as a constructor – an exception is thrown if you invoke it via
The only useful method that symbols have is
|Conversion to||Explicit conversion||Coercion (implicit conversion)|
The global object
Symbol has several properties that serve as constants for so-called well-known symbols. These symbols let you configure how ES6 treats an object, by using them as property keys. This is a list of all well-known symbols:
Ccustomize the behavior of
x instanceof C.
Object.prototype.toString()to compute the default string description of an object
for-ofloop and the spread operator (
...)). The method returns an iterator. Details: chapter “Iterables and iterators”.
String.prototype.match(x, ···)is forwarded to
String.prototype.replace(x, ···)is forwarded to
String.prototype.search(x, ···)is forwarded to
String.prototype.split(x, ···)is forwarded to
The details are explained in Sect. “String methods that delegate regular expression work to their parameters” in the chapter on strings.
Array.prototype.map()) create objects that are similar to
this. The details are explained in the chapter on classes.
Array.prototype.concat()adds the indexed elements of an object to its result (“spreading”) or the object as a single element (details are explained in the chapter on Arrays).
If you want a symbol to be the same in all realms, you need to use the global symbol registry, via the following two methods:
Symbol.for(str) : symbol
strin the registry. If
strisn’t in the registry yet, a new symbol is created and filed in the registry under the key
Symbol.keyFor(sym) : string
symin the registry. If
symisn’t in the registry, this method returns
undefined. This method can be used to serialize symbols (e.g. to JSON).