Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it a good practice to use ES6 Symbol as unique ids?

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()}
        ]
like image 722
wuct Avatar asked Sep 03 '15 06:09

wuct


People also ask

What are the advantage of using symbols in ES6?

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().

When should I use a symbol in JS?

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.

What is unique ID in JavaScript?

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.

What is a symbol ECMAScript?

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.


1 Answers

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.

like image 185
Gary Avatar answered Sep 26 '22 16:09

Gary