Symbol Type in Javascript
Symbol
is 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 key
as the name. Multiple calls of Symbol.for
return 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.
-
There are many system symbols used by JavaScript which are accessible as
Symbol.*
. We can use them to alter some built-in behaviors. For instance, later in the tutorial we’ll useSymbol.iterator
for iterables,Symbol.toPrimitive
to setup object-to-primitive conversion and so on.
Comments
Post a Comment