Simplest possible way to generate unique ID in Javascript

Paulius Repšys
2 min readOct 13, 2021

--

In Javascript applications, sometimes we need a way to generate a unique ID.

It may be used to set ID attribute for dynamically created DOM elements, to pass trackId for function callbacks etc.

Let’s google it!

If we search how others do it, we would find a tone of examples “How to make complex enough string that is highly unlikely to be dublicated”. Usually they involve using of Math.random():

const uniqueId = Math.random().toString(36).substr(2, 9);

Problem with Math.random() is that it does not guarantee unique output. Here is one developer’s comment about above method:

This is okay for generating less than 10 thousand unique IDs, but any more than 10 thousand and you are going to run into collisions.

To fix that, people add Date.now() to the above method:

const uniqueId = () => {
const dateString = Date.now().toString(36);
const randomness = Math.random().toString(36).substr(2);
return dateString + randomness;
};

However Date.now() will not guarantee different output if function is called multiple times in 1 millisecond.

As it eventually turns out, there is no good way to generate a unique ID that would work with 100% reliability .

Simple solution to (not)complex problem

If you are going to store generated ID in database or localstorage and fetch between sessions, you are out of luck and should probably think about third party lib like “uuid”.

However, in most cases uniqueness is only required during single session (until page is refreshed).

So here is a simple solution to the problem:

let id = 0;export function getUniqueId(): string {
return id++ + '';
}

At first, for you it may seem stupid that I suggest such simple and easy solution, but I can tell that when I looked for solutions over internet, noone recommended anything similar, and in many cases this solution is more than enough and will work perfectly.

--

--

Responses (1)