Open In App

How to create a GUID / UUID in JavaScript ?

A GUID (Globally Unique Identifier) or UUID (Universally Unique Identifier) is a 128-bit unique identifier that is used in computer systems to identify resources such as files, objects, and components. A GUID is generated randomly and is very unlikely to be duplicated. It is used in various applications and systems such as databases, web applications, and operating systems.

It is typically represented as a string of 32 hexadecimal digits, such as “550e8400-e29b-11d4-a716-446655440000”. GUIDs are generated using a combination of timestamps, random numbers, and network address information.



Syntax:

xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx

Parameters:

Approach

Example 1: In this example, a concise JavaScript function generates a random UUID following the ‘xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx’ pattern. The UUID includes randomly generated hexadecimal digits, a fixed ‘4’ for version indication, and a digit following a specific pattern denoted by ‘y’. The function then prints the generated UUID to the console using console.log(random_uuid).




// Generate a random UUID
const random_uuid = uuidv4();
 
// Print the UUID
console.log(random_uuid);
 
function uuidv4() {
    return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
    .replace(/[xy]/g, function (c) {
        const r = Math.random() * 16 | 0,
            v = c == 'x' ? r : (r & 0x3 | 0x8);
        return v.toString(16);
    });
}

Output

8e8679e3-02b1-410b-9399-2c1e5606a971

Example 2: In this example, a succinct JavaScript code snippet utilizes the ‘uuid’ library to generate a random UUID. The uuidv4 function from the library is assigned to random_uuid, and the generated UUID is printed to the console with console.log(random_uuid). The ‘uuid’ library simplifies the process of UUID generation in a concise manner.




const { v4: uuidv4 } = require('uuid');
 
// Generate a random UUID
const random_uuid = uuidv4();
 
// Print the UUID
console.log(random_uuid);

Output:

93243b0e-6fbf-4a68-a6c1-6da4b4e3c3e4

Article Tags :