How to Create GUID / UUID in JavaScript?


The Globally Unique Identifier (GUID) or (Universally Unique Identifier) is a 16-byte or 128- bit binary value that is used as an identifier standard for software construction. This 128-bit number is represented in a human-readable format by using the canonical format of hexadecimal strings. One example is like: de305d84-75c4-431d-acc2-eb6b0e5f6014. In this article, we shall cover how we can use javascript functionality to generate GUID or UUID. There are a few different methods, covered one by one:

By using random number generation

Example

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

for(var i = 0; i<5; i++) {
   console.log( "A sample GUID / UUID: ",generate_uuidv4() );
}

Output

A sample GUID / UUID:  3b869420-6618-43dd-a351-6373ed8ffb48
A sample GUID / UUID:  5d3459b9-d5f1-49ca-a356-d315b314b7eb
A sample GUID / UUID:  19d3ea72-24c7-46e8-177c-a052eb9bc677
A sample GUID / UUID:  e3f70fb6-951a-4ee1-b3a2-3173bf7e3a91
A sample GUID / UUID:  eac986d7-2d1d-40a4-29eb-92eb131bd0cc

In the above example, we are generating five UUIDs using random number generation. Since the above method relies on Math.Random() function, this can be good to generate GUID or UUID but this is not a high-quality random number generator. There is always a chance to collide two UUIDs by the same random numbers. There is a little twist on Math.Random() can make it a more reliable UUID or GUID generator. In that case, we can incorporate the date and time with it.

Example

function generate_uuidv4() {
   var dt = new Date().getTime();
   return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g,
   function( c ) {
      var rnd = Math.random() * 16;//random number in range 0 to 16
      rnd = (dt + rnd)%16 | 0;
      dt = Math.floor(dt/16);
      return (c === 'x' ? rnd : (rnd & 0x3 | 0x8)).toString(16);
   });
}

for(var i = 0; i<5; i++) {
   console.log( "A sample GUID / UUID: ",generate_uuidv4() );
}

Output

A sample GUID / UUID:  7a83193c-9624-48e2-a223-e910878c89c5
A sample GUID / UUID:  c8e49a59-16a4-4d22-97fc-cdafffba2707
A sample GUID / UUID:  7feea4a6-59d5-4f0e-b7b7-b5cd2069fa0f
A sample GUID / UUID:  f244e83c-5af5-483b-8fdd-39d56c6b16ee
A sample GUID / UUID:  bc2e2167-91d5-4f53-afc3-af9efdc14e56

Let us see another type of method to generate GUID / UUID by using pseudo-random number generation. In this example, a randomly 16-digit hexadecimal character sequence is generated, then for the specified places (for the place 12 to 15, set it to 4), (for 6-7th places, put constant 01. And at appropriate places insert a hyphen (‘-‘) to maintain the correct format.

By using Pseudo-random numbers

Example

function generate_uuidv4() {
   var id_str = [];
   var hxDigits = "0123456789abcdef";
   for (var i = 0; i < 36; i++) {
      id_str[i] = hxDigits.substr(Math.floor(Math.random() * 0x10), 1);
   }
   id_str[14] = "4"; // bits 12-15 is for time_hi_and_version field, set to to 0010
   
   id_str[19] = hxDigits.substr((id_str[19] & 0x3) | 0x8, 1); // bits 6-7 for the clock_seq_hi_and_reserved to 01
   
   id_str[8] = id_str[13] = id_str[18] = id_str[23] = "-";
  
   var guid = id_str.join("");
   return guid;
}
for(var i = 0; i<5; i++) {
   console.log( "A sample GUID / UUID: ",generate_uuidv4() );
}

Output

A sample GUID / UUID:  b5106962-5bc5-46dc-b74e-7a3fd0584fc0
A sample GUID / UUID:  5fdfa0e1-4251-4ae6-bafc-b162e032ab48
A sample GUID / UUID:  de644da7-2dc4-499f-82fa-618f5b6f133e
A sample GUID / UUID:  cc5ce77f-18dd-46ba-8762-1cc7cf9c7a7f
A sample GUID / UUID:  1708db50-0d8d-4fcc-8e7e-5cfc23387c6f

Let us see another type of method to generate GUID / UUID by using pseudo-random number generation. This is the fast method, in this method the UUID string is generated with two halves by generating numbers between 2 and 15. Reformatting can be done later

Example

function generate_uuidv4() {
   return Math.random().toString(36).substring(2, 15) +
   Math.random().toString(36).substring(2, 15);
}
for(var i = 0; i<5; i++) {
   console.log( "A sample GUID / UUID: ",generate_uuidv4() );
}

Output

A sample GUID / UUID:  8kyxdvlm8by3licwpf081c
A sample GUID / UUID:  coemu70fbbw9e8gsvvw8aq
A sample GUID / UUID:  41kamutwz52izjiw1h769
A sample GUID / UUID:  r3e4app5nfsphj3wa7sa8
A sample GUID / UUID:  463olfnw767sr9hy0hlcn

Conclusion

UUID or GUID is used as global identifier standards. These are 128bit (16-byte) binary strings with different segments. There are many different methods to generate the UUID / GUID through JavaScript. Here random number generation-based methods are described in detail. In the first method simple Math.Random() is used but as this function may create the same numbers twice, that’s why the DateTime parameter is being used to give a salt for generating the new set of UUIDs which are more likely to be distinct.

Arnab Chakraborty
Arnab Chakraborty

Corporate Trainer

Updated on: 04-Apr-2023

8K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements