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...

Leave a Reply

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