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

function createGUID() {
  function random() {
    return Math.floor((1 + Math.random()) * 0x10000)
      .toString(16)
      .substring(1);
  }
  return random() + random() + '-' + random() + '-' + random() + '-' +
    random() + '-' + random() + random() + random();
}

Usage:

var uuid = createGUID();

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.

'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    var r = Math.random()*16|0, v = c == 'x' ? r : (r&0x3|0x8);
    return v.toString(16);
});

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.

function generateUUID(){
    var dt = new Date().getTime();
    if(window.performance && typeof window.performance.now === "function"){
        dt += performance.now(); //use high-precision timer if available
    }
    var uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
        var r = (dt + Math.random()*16)%16 | 0;
        dt = Math.floor(d/16);
        return (c=='x' ? r : (r&0x3|0x8)).toString(16);
    });
    return uuid;
}
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

Leave a Reply

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

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like