Generating UUID in Javascript

JavaScript is a lightweight, interpreted programming language, well-known for its scripting capabilities on web pages. It is a prototype-based, multi-paradigm, single-threaded, dynamic language that supports object-oriented, imperative, and declarative (e.g., functional programming) styles. JavaScript's dynamic features include runtime object construction, variable argument lists, function variables, dynamic script creation (via eval), object introspection (via for...in and Object utilities), and source-code recovery (JavaScript functions store their source text and can be retrieved through toString()). It adheres to the ECMAScript standards set by Ecma International, and although most browsers implement JavaScript, there are variations due to the different engines they use to interpret and execute JavaScript code.

The latest versions of JavaScript continuously introduce new features, such as Lambda expressions and the Stream API, making it more suitable for functional and concurrent programming. These features, combined with its cross-platform capabilities and a robust standard library, make JavaScript an ideal choice for developing a variety of applications, from desktop software to web services, and from mobile apps to game development.

1. Using the Third-Party Library uuid

The simplest and most popular method is to use a third-party library named uuid, which provides a straightforward API for generating various versions of UUIDs.

First, you need to install this library:

npm install uuid

Then, you can use it in your JavaScript code like this:

const { v4: uuidv4 } = require("uuid");

const myUUID = uuidv4();
console.log(myUUID);

In this example, the uuidv4 function generates a random-based UUID (compliant with RFC 4122 version 4). This library also provides functions for generating UUIDs of versions v1, v3, and v5.

2. Manual Implementation of UUID v4

If you prefer not to introduce external dependencies, you can manually implement a function to generate UUID v4.

function generateUUIDv4() {
  return "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);
  });
}

const myUUID = generateUUIDv4();
console.log(myUUID);

In this function, we use a template string to construct the UUID and replace 'x' and 'y' with regular expressions to generate the correct hexadecimal values. For 'x', we generate a random number between 0 and 15; for 'y', we generate a random number that is either 8, 9, A, or B to ensure the generated UUID meets the requirements of version 4.

3. Using the Crypto API

In modern browsers, you can use the Web Crypto API to generate a cryptographically secure random UUID.

async function generateUUIDv4() {
  const array = new Uint8Array(16);
  await crypto.getRandomValues(array);
  // Set the version to 4 (0100)
  array[6] = (array[6] & 0x0f) | 0x40;
  // Set the variant to 10 (binary: 10xx)
  array[8] = (array[8] & 0x3f) | 0x80;
  return (
    array[0].toString(16).padStart(2, "0") +
    array[1].toString(16).padStart(2, "0") +
    array[2].toString(16).padStart(2, "0") +
    array[3].toString(16).padStart(2, "0") +
    "-" +
    array[4].toString(16).padStart(2, "0") +
    array[5].toString(16).padStart(2, "0") +
    "-" +
    array[6].toString(16).padStart(2, "0") +
    array[7].toString(16).padStart(2, "0") +
    "-" +
    array[8].toString(16).padStart(2, "0") +
    array[9].toString(16).padStart(2, "0") +
    "-" +
    array[10].toString(16).padStart(2, "0") +
    array[11].toString(16).padStart(2, "0") +
    array[12].toString(16).padStart(2, "0") +
    array[13].toString(16).padStart(2, "0") +
    array[14].toString(16).padStart(2, "0") +
    array[15].toString(16).padStart(2, "0")
  ).toUpperCase();
}

generateUUIDv4().then(console.log);

This code uses the crypto.getRandomValues() method to fill a 16-byte array, then performs bitwise operations on the array according to the UUID format to generate a UUID string that complies with RFC 4122 version 4.