loading...

How to Generate Unique ID in JavaScript

rahmanfadhil profile image Rahman Fadhil Originally published at rahmanfadhil.com ・2 min read

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
const uuidv4 = require("uuid/v4")

uuidv4()

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

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)

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

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

Result:

1576996323453

Posted on by:

rahmanfadhil profile

Rahman Fadhil

@rahmanfadhil

Developer, Instructor, and Content Creator

Discussion

markdown guide
 

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.

 

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

 

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

 

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.

 

UUID is the goto solution for JS at least.

 

You can also use UUID Generator, a web-based tool built on top of the same library to generate UUIDs on the browser. It supports both UUID version 1 (timestamp) and 4 (random).

 
 

I was building a local db with npmjs.com/package/lowdb just for testing purposes and the Date.now() is more than enough to get an unique id. Thanks Rahman :)

 
 

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

greetings from indonesia :)

 

No offense Rahman but this article adds to the information noise of the Internet. What we all need is quality over quantity otherwise we're wasting resources. I'm in favour of knowledge and experience sharing but have a feeling that you published this mainly to show somewhere someone that you're authoring. It'd be much more valuable if you read the already published articles on this to see what you can expand on etc. Again, no hard feelings and ego asife. You'll see yourself what I mean when you want to research a given problem and you get many search results like this.

 

Or he could just be wanting to post some quick tips on ID generation he knows about. People should be empowered to share what they know so that developers of any skill level can take advantage.