Since Symbol
is a unique and immutable data type, a common use case for Symbol
is object properties. However, is it a good practice to use it as a unique id? For example:
const list = [
{id: Symbol()},
{id: Symbol()}
]
Symbols provide 'an extra level of privacy', by preventing the keys/properties of an object from being exposed through some popular methods such as Object. keys() and JSON. stringify().
Symbols are often used to add unique property keys to an object that won't collide with keys any other code might add to the object, and which are hidden from any mechanisms other code will typically use to access the object. That enables a form of weak encapsulation, or a weak form of information hiding.
Introduction to JavaScript UUID. A universally unique identifier (UUID) is an identifier of the 128-bit value that is used in the construction of software. Each bit present in the value differs by the meaning as several variants are considered.
Symbols are a new primitive type in ECMAScript 6. They are created via a factory function: const mySymbol = Symbol ( 'mySymbol' ); Every time you call the factory function, a new and unique symbol is created.
This depends entirely on your needs. If you only need them as an identifier in your own codebase, they're fine, certainly better than generating a random ID.
A major downside to using Symbol()
though is that they aren't serializable. There isn't a way to share the value of Symbol()
across networks/processes or save them to disk/databases.
For most cases it's probably better to use auto-incrementing IDs.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With