Understanding the Basics of Symbols
Symbol(). Despite having no descriptions and being created in a similar manner, they are not equal (
mySymbol === anotherSymbol results in
false). This uniqueness is the core feature of Symbols, making them ideal for unique identifiers.
Creating Symbols with Descriptions
While Symbols are unique, adding a description can aid in debugging and code readability.
Code Example: Symbols with Descriptions
Explanation: Here, two Symbols are created with identical descriptions. The key takeaway is that even when Symbols have the same description, they remain unique (
sym1 === sym2 is
false). The description is merely a way to provide readable identification for debugging purposes, as shown by
Symbols as Object Keys
One of the primary uses of Symbols is as keys for object properties, ensuring property uniqueness and avoiding accidental property overwrites.
Code Example: Using Symbols as Object Keys
Explanation: In this example, a Symbol
SIZE is used as a key for an object property. This ensures that the
SIZE property is unique and won't conflict with any other property named
area method of the
square object uses this unique key to calculate the area of a square, demonstrating how Symbols can be used to avoid property name clashes.
Symbol.* which serve various specific purposes.
Example: Using Well-Known Symbols
Explanation: This snippet shows the use of a well-known Symbol,
Symbol.for and Symbol.keyFor Methods
Symbol.for(key) method searches for existing symbols with the given key and returns it if found; otherwise, it creates a new symbol.
Symbol.keyFor(symbol) retrieves a shared symbol key from the global symbol registry.
Code Example: Symbol.for and Symbol.keyFor
Explanation: In this code,
Symbol.for('global') searches for a Symbol with the key
'global' in the global symbol registry. If it doesn't exist, it creates and stores it in the registry. This makes
globalSym a reusable symbol across different parts of the code.
Symbol.keyFor() is used to retrieve the key of a global symbol. It returns the key for
localSym is not a global symbol but a locally created one.