DEV Community

Cover image for Unique ID in Javascript
Aram
Aram

Posted on

Unique ID in Javascript

Probably you also had cases where you needed a unique ID, and using uuid was not practical.

So What can be used as an alternative to this? Let's look at some cases.

Math.random

As we know, the Math.random function generates random numbers.

When you try to assign a unique ID using Math.random immediately begs the question.

Is there any chance the generated number can be repeated and you will not get a unique ID?
The chance is small but still there.

Can I use it?
Yes you can, but not worth it.

What should we do in such a case?
Use the options below.

Date.now

What is Date.now?

The Date.now static method returns the number of milliseconds elapsed since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC.

This means that the returned numbers cannot be repeated. (unless of course, you have a secret method to go back in time)

The only case where the Date.now method can return the same digit is, when you call Date.now() function before a

few (depends on the execution environment)
milliseconds have passed.

When can this happen?

For example, you need to have a list of ids with unique ids.
The first thing that comes to mind is to write a for loop.


WRONG APPROACH

const idList = [];
for (let i = 0; i < 10; i++) {
  idList[i] = Date.now();
}
Enter fullscreen mode Exit fullscreen mode

Most likely you will get the same ids.


RIGHT APPROACH

const idList = [];
const ms = 10; // depends on the execution environment
const interval = setInterval(() => {
  idList.push(Date.now());
  if (idList.length === 10) {
    clearInterval(interval);
  }
}, ms);
Enter fullscreen mode Exit fullscreen mode

This way you can get unique list of ids.


But that's not all, there are even more advanced options.

Crypto.randomUUID

The self.crypto.randomUUID method of the Crypto interface is used to generate a v4 UUID using a cryptographically secure random number generator.

const idList = [];

for (let i = 0; i < 10; i++) {
    const uuid = self.crypto.randomUUID();
    idList[i] = uuid;
}
Enter fullscreen mode Exit fullscreen mode

But you must be sure that the runtime supports Crypto.

It all depends on what problem you are solving.
...https://coderolls.com/uuid-in-java/

Top comments (0)