Create GUID/UUID in JavaScript

There might be situations where you would be creating GUID in Javascript, Currently JavaScript doesn’t have any Built-in method to generate the GUID/UUID. We could use Math.random() or Date().getTime() and generate a random GUID in JavaScript.

Example 1:

Create GUID/UUID in JavaScript


If you look at the above method we are using the Math.random() and generating the random number and converting it to string. Every time we make a call to random() function it returns a unique 4 character string and the same is appended to generate GUID/UUID no.

Example 2:

Generate UUID in JavaScript using RFC4122 version 4 complaint and Regular Expression

Below example is the most compact and in line with RFC4122 version 4 compliant.

Example 3:

Generate GUID in JavaScript using Date and Math.random()

The below code uses current date and time and also adds up with the random number generated.

Note: All the above methods are highly dependent on the Math.random() method and unique number it generates. Math.random() is not recommended for high-quality Random Number Generation(RNG).

There is one in a million chance of repetition with 3.26×1015 version 4 RFC4122 UUIDs

You may also like...

2 Responses

  1. You may want to try KSUID, it’s a GUID that works really well on distributed systems.
    It’s also ordered…

  2. Michael J. Ryan says:

    With crypto, modern browsers…

    function createUUID() {
    const fmt = ‘xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx’;
    const rnd = Array.from(crypto.getRandomValues(new Uint8Array(32)))
    .map(n => n&0xf);
    const rk = (c,r) => ((c == ‘x’ ? r : (r&0x3|0x8)).toString(16));
    return fmt.replace(/[xy]/g, c => rk(c, rnd.pop()));

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.