3 ways to generate GUID in javascript

GUIDs are the Globally Unique Identifier which usually refers to the Microsoft implementation of UUID (Universally Unique Identifier) standard. It is a 128 bits long hexadecimal which are guaranteed to be unique. A GUID can be used for books, cars, people or any item in the universe. A practical example of GUID usage in google search indexes or any big sites like amazon, facebook etc.

According to wikipedia, total number of GUID is 2122 (approximately 5.3×1036)

A typical GUID key will look like this:


And you can generate the GUID by various ways:

1. GUID based on random number

function guid() {  
  function s4() {
    return Math.floor((1 + Math.random()) * 0x10000)
  return s4() + s4() + '-' + s4() + '-' + s4() + '-' +
    s4() + '-' + s4() + s4() + s4();

2. The one line GUID solution

'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);

3. Time based GUID combined with random number

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

However, note that the above solution are quicker way to generate GUID without any dependencies. If you need a valid RFC4122 version GUID, you may better off using libraries like node-uuid.