Symbol
Symbols are created using `Symbol(optionalDesc)`. Symbols are always different values. They are mainly used for two things: to create "hidden" object properties and to alter some built-in behaviors.
Symbols
Symbols are guaranteed to be unique. For example, we can create two symbols with the same description but they will not be equal:
Use Case 1: Create "hidden" object props
Symbols can be used as object properties. Additionally, symbols are not enumerated (for example, they are ignored in for ... in
loop and Object.keys()
method). This allows us to create kind of "hidden" properties that prevent accidantal access.
Use Case 2: System Symbols
There are many JavaScript symbols that are accessible by Symbol.*
:
etc...
For example, with the help of Symbol.iterator
we can specify iterator for an object:
Symbol.for
There is also global Symbol registry which we can use with the help of Symbol.for()
. This function takes a string argument and returns Symbol value that is associated with the string you pass. In case there was no Symbol associated with that string, the new one is created and returned.
Links
Last updated