DEV Community

Rahman Fadhil
Rahman Fadhil

Posted on • Originally published at rahmanfadhil.com

How to Generate Unique ID in JavaScript

Read the original article here

There are several ways to generate unique identifier in JavaScript. This could very useful in many cases, such as rendering list efficiently, or storing documents or records in database.

Using UUID

UUID is the abbreviation of univerally unique identifier, which is an identification number to uniquely identify something. The main idea of this thing is everytime we generate this numbers, it will be universally unique, which means no one could generate the exact same id as yours.

I personally prefer this approach in any case. In JavaScript, we can use a library called uuid to generate UUID.

$ npm install uuid
Enter fullscreen mode Exit fullscreen mode
const uuidv4 = require("uuid/v4")

uuidv4()
Enter fullscreen mode Exit fullscreen mode

UUID has several versions, but the version that appropriate for generating unique id is version 4. And, that code will generate something like this.

1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed
Enter fullscreen mode Exit fullscreen mode

Using Math.random

Math.random is a JavaScript built-in function which allows us to generate a random number. Which means that everytime we run it, it will return a unique combination of numbers.

Math.floor(Math.random() * 100)
Enter fullscreen mode Exit fullscreen mode

Math.random always returns a decimal number, so we need to rounding off that number first. By multiply it with 100, it will return any number between 0 to 99. You can increase the number if you want to get better result.

Result:

52
Enter fullscreen mode Exit fullscreen mode

Using Date.now

Date.now is another JavaScript built-in function which allows us to get the number of miliseconds elapsed since January 1, 1970.

Date.now()
Enter fullscreen mode Exit fullscreen mode

Result:

1576996323453
Enter fullscreen mode Exit fullscreen mode

Top comments (30)

Collapse
 
peledzohar profile image
Zohar Peled • Edited

A random number is not the same as a unique number. There is absolutely no guarantee of uniqueness in a collection of randomly generated numbers.

DateTime.Now() will also not generate a unique number, unless guaranteed not to run at the exact same millisecond. for quite a while now, computers are fast enough to run a few iteration of a loop within a single millisecond.

Collapse
 
coderkearns profile image
coderkearns

You could decrease the chances by using multiple of the author's ways:

Maybe

function uniqueID() {
return Math.floor(Math.random() * Date.now())
}

You could even string multiple randoms together:

Math.floor(Math.random() * Math.floor(Math.random() * Date.now()))

Collapse
 
wolffe profile image
Ciprian Popescu

Depending on the application, this is the right way to do it. In my case, I don't have a loop, I have several elements being displayed on subsequent clicks, and there's several seconds between each click. So there's zero chances of an identical ID.

Collapse
 
abbatyya profile image
abbatyya

thank you, this work also. to also include string i use Math.floor(Math.random() * Date.now()).toString(16)

Collapse
 
mitchneutron profile image
Mitchell Mortensen

While yes it's theoretically possible for UUID to produce a duplicate, it is statistically improbable (read: impossible) to do so, even when striving for such and taking into account the birthday paradox. According to wikipedia:

"Only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. Or, to put it another way, the probability of one duplicate would be about 50% if every person on earth owned 600 million UUIDs."
en.wikipedia.org/wiki/Universally_...

You actually more likely to have a totally unique ID than to have gotten one that anyone has ever seen in the entire world! And it will be this way until the sun runs out of juice.

UUID is the only one that should be used. Date.now() is terrible for reasons that Zohar mentions.

Collapse
 
rahmanfadhil profile image
Rahman Fadhil

I kind of agree 🤔

I think the title should be "how to generate random id"

But, at least I put UUID as the most recommended approach

Collapse
 
peledzohar profile image
Zohar Peled

In fact, random numbers probability of uniqueness is actually a lot smaller than what one can expect, without knowledge of what's called the birthday problem.

In a nutshell - Take a group of random people. What are the chances two of them was born in the same date (day and month, year not included)?

Turns out, that if the group contains 32 people, that chance is 50%. With 70 people in the group, its 99.9%.

So the chances of getting the same random number twice when your range is between 0 and 100 increase rapidly the larger the group is.

Collapse
 
siddharthshyniben profile image
Siddharth

I just tried the Date.now() method, and even when I ran a loop 1000 times, all the "unique" numbers were the same.

Collapse
 
snakebite382 profile image
Caelin Limerick

That's because it all ran within the same millisecond. Date.now() returns time since epoch in ms, so if you run it twice within 1ms the number will be the same since the time since epoch in ms is the same. This is why UUID is a much better approach (like literally the best, universally agreed on approach) however you can still fix this by adding a 1ms delay in your loop, or doing something like multiply by math.random() to add some varation.

Thread Thread
 
siddharthshyniben profile image
Siddharth

Yeah that's right!

Also, UUID is slowly being replaced by NanoID - it's faster, smaller (both package size and IDs), URL friendly, and cryptographically more secure (although both of them are secure enough for that to be irrelevant)

Collapse
 
forkbomb profile image
Joe Buckle

UUID is the goto solution for JS at least.

Collapse
 
roblevintennis profile image
Rob Levin

I was researching this and while I agree uuid package is probably least human error prone, it does mean potentially adding another package.

It seems like utilizing Date.now().toString or perhaps new Date().getTime() or similar and also Math.random could do the trick:

const uid = () =>
  String(
    Date.now().toString(32) +
      Math.random().toString(16)
  ).replace(/\./g, '')
Enter fullscreen mode Exit fullscreen mode

We can test it by adding generated to a map and comparing size:

const size = 1000000
const set = new Set(new Array(size)
  .fill(0)
  .map(() => uid()))

console.log(
  size === set.size ? 'all ids are unique' : `not unique records ${size - set.size}`
)
Enter fullscreen mode Exit fullscreen mode


__

Collapse
 
gregorip02 profile image
Gregori Piñeres

Your script now are in my personal helpers file. thanks.

Image description

Collapse
 
justingolden21 profile image
Justin Golden

This is the best comment here, and with only one like! A perfect small utility and a way to test it, all super intuitive and functional : )

Collapse
 
sujalshah profile image
Sujal Shah

There is 1 inbuilt method which returns randomUUID
window.crypto.randomUUID()

No 3rd party library, Super fast ⌛

Collapse
 
lpix11 profile image
Mohamed Johnson

For anyone trying out the first example with uuid, it works just fine and the module respects the standards, it just evolved and I guess the post did not 😅.
Anyhow here's the correct implementation

import { v4 as uuidv4 } from 'uuid';
uuidv4(); // ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'

// ... or using CommonJS syntax:
const { v4: uuidv4 } = require('uuid');
uuidv4(); // ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
Enter fullscreen mode Exit fullscreen mode

Feel free to test it out ^^

Collapse
 
blendsmile profile image
Blend_Smile • Edited

i never think of using millisecond to generate an id, nice approach!

greetings from indonesia :)

Collapse
 
guiabc profile image
Gui • Edited

It's my way to generate a 100% guaranted unique and random local id:

var MyLib = {
    //Max id guaranted to be unique will be 999 999 999. 
    //Add more zeros to increase the value.
    lastUid : 100000000, 

    generateUid : function(){
        this.lastUid++;

        //Way to get a random int value betwen min and max: 
        //Math.floor(Math.random() * (max - min) ) + min;
        var randValue = Math.floor(Math.random() * (99999 - 10000)) + 10000;

        return Number(this.lastUid.toString() + randValue);
    }
};

console.log(MyLib.generateUid());
Enter fullscreen mode Exit fullscreen mode
Collapse
 
urielbitton profile image
Uriel Bitton

Math.random does neither generate truly random numbers nor are they unique. Its randomness is of course based on the range you provide and that is its own shortcoming. The other methdos you mentioned are a lot more unique and more random.
Cheers!

Collapse
 
awinooliyo profile image
Erick Otieno Awino • Edited

how about using crypto.randomUUID(), which is part of the Web Crypto API that generates a UUIDv4. I read that it is fast, secure, and simple to use. Here is an example:
const uuid = crypto.randomUUID();
console.log (uuid); // a random and unique ID.

Collapse
 
rohansawant profile image
Rohan Sawant

What a great read!

🔥

Collapse
 
pfedprog profile image
Pavel Fedotov

The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.

developer.mozilla.org/en-US/docs/W...

Some comments may only be visible to logged-in visitors. Sign in to view all comments.