Symbolis a primitive type for unique identifiers.
Symbols are created with
Symbol()call with an optional description.
Symbols are always different values, even if they have the same name. If we want same-named symbols to be equal, then we should use the global registry:
Symbol.for(key)returns (creates if needed) a global symbol with
keyas the name. Multiple calls of
Symbol.forreturn exactly the same symbol.
Symbols have two main use cases:
“Hidden” object properties.
If we want to add a property into an object that “belongs” to another
script or a library, we can create a symbol and use it as a property
key. A symbolic property does not appear in
for..in, so it won’t be occasionally listed. Also it won’t be accessed directly, because another script does not have our symbol, so it will not occasionally intervene into its actions.
So we can “covertly” hide something into objects that we need, but others should not see, using symbolic properties.
Symbol.*. We can use them to alter some built-in behaviors. For instance, later in the tutorial we’ll use
Symbol.toPrimitiveto setup object-to-primitive conversion and so on.