Create a unique ID in JavaScript

OpenJavaScript 0

Last updated: March 30, 2022.

In JavaScript or Node, it is often necessary to create a unique ID to identify a user or a session.

A sufficiently unique ID for any purpose can be created by combining two bits of information.

Creating a unique ID

Part 1: Timestamp

The first is the output of Date.now(). This returns the number of milliseconds that have passed since midnight on January 1, 1970 (UTC):

const time = Date.now();

The advantage of using this metric as part of the ID is that the ID will contain a precise timestamp of its creation.

Of course, a timestamp is not enough to guarantee that an ID is unique: What if two IDs are generated at exactly the same time, to the millisecond? Even though it is unlikely, it is best not to take chances!

Part 2: Random number

To ensure that two or more IDs generated at the same time are unique, we can use the in-built Math.random() function to generate a second part of the ID. A random number between 0 and 1,000,000,000 (one billion) should do it:

const randomNumber = Math.floor(Math.random() * 1000000001);

Creating a unique ID function

Defining the function

Now all we have to do is join these two values to create a unique ID.

And, because we likely want to call it multiple times, we should place this code inside a function to make it reusable:

function generateID() {
    // Generate timestamp and random number:
    const time = Date.now();
    const randomNumber = Math.floor(Math.random() * 1000000001);

    // Merge both with string underscore (forces string)
    const uniqueId = time + "_" + randomNumber;

    // Make function return the result
    return uniqueId;
} 

Usage example

Now, you can call the function whenever and as many times as you need to within your project to generate a unique ID:

generateID(); // 1648376206198_612111379
generateID(); // 1648376206198_267310705
generateID(); // 1648376206198_324813030

Notice that in the above code, each ID is generated at exactly the same. But the random number appended to the timestamp ensures that the ID is still unique.

Related links