A GUID (Globally Unique Identifier) or UUID (Universally Unique Identifier) in JavaScript is a string that represents a universally unique identifier. These identifiers are typically used to uniquely identify objects or entities in a system, making sure that each identifier is unique from any other.
GUIDs are unique codes made up of 32 characters, like “c4c2e941-e024-43ec-9764-bd413c26aa30”. They are created using a mix of time, random numbers, and computer network details.
Creating a GUID or UUID in JavaScript can be done using various methods. Depending on your project’s environment and requirements, you can choose the method that best suits your needs.
Below are several ways to generate GUIDs/UUIDs in JavaScript.
Using the uuid Package
You can generate a GUID/UUID in JavaScript using the uuid
package.
First, install the package via npm.
npm install uuid
Then, in your JavaScript code:
const { v4: uuidv4 } = require('uuid'); const uuid = uuidv4(); console.log(uuid);
This code uses version 4 of the UUID, which is based on random numbers.
Output:
f212a1fb-f8e6-459c-a3d1-e23e54557eef
Using Math.random()
If you prefer not to use external packages, JavaScript’s Math.random()
function can be used to generate a GUID/UUID.
function createGuid() { function _p8(s) { var p = (Math.random().toString(16) + "000000000").substr(2,8); return s ? "-" + p.substr(0,4) + "-" + p.substr(4,4) : p; } return _p8() + _p8(true) + _p8(true) + _p8(); } var guid = createGuid(); console.log(guid);
This function will generate a GUID by creating random strings of characters and arranging them in a specific pattern. The _p8
function will generate a random string, and the createGuid
function will combine these random strings to form a GUID.
The resulting guid
variable holds the generated unique identifier.
Output:
b8ab2a62-4cc0-5b7a-1717-67c619215885
Here are some additional methods using the Math.random()
to generate GUID/UUID.
Simplified Random GUID
Another way of using Math.random()
to create a GUID. This method is a bit more concise.
function createGuid() { function S4() { // Generates a random number, adds 1, multiplies by 0x10000, converts to hexadecimal, // removes the first character (before the decimal point), and ensures it has at least 4 characters return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1); } // Combines several randomly generated strings with hyphens in specific positions to form a GUID return (S4() + S4() + "-" + S4() + "-4" + S4().substr(0, 3) + "-" + S4() + "-" + S4() + S4() + S4()).toLowerCase(); } // Calls the createGuid function to generate a GUID and stores it in the 'guid' variable var guid = createGuid(); console.log(guid);
This function will generate a GUID by creating random 4-character hexadecimal strings and arranging them in a specific pattern.
The resulting guid
variable will hold the generated unique identifier, and it will be printed to the console for reference.
Enhanced Random GUID
This method is similar to the above method but uses a different approach to generate the segments of the GUID.
function createGuid() { function s4() { // Generates a random decimal number between 0 and 1, adds 1, multiplies it by 0x10000 // to shift the decimal place to include 4 characters, applies Math.floor to round down, // converts the number to a string in base 16, and removes the first character (substring(1)) return Math.floor((1 + Math.random()) * 0x10000).toString(16).substring(1); } // Constructs and returns the GUID by combining random hexadecimal strings in a specific pattern return ( s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4() ); } var guid = createGuid(); console.log(guid);
The createGuid
function will generate a GUID by creating random strings of hexadecimal characters and arranging them in a specific pattern as defined by the GUID format.
The s4
function will generate a random string of 4 hexadecimal characters, and these strings will be concatenated together with hyphens to form a complete GUID.
The resulting GUID will then be stored in the variable guid
, and it will be printed to the console using console.log(guid)
.
Output:
0ab7d284-ac5d-b2bc-8d09-676d3a1b3fe7
Using Regular Expressions
This method involves using a template string and a regular expression to generate the GUID.
function createGuid() { return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) { // Generates a random hexadecimal digit (r) for 'x' placeholders // If the placeholder is 'x', it uses the random value; if 'y', it modifies the random value to conform to the UUID format var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8); // Converts the generated value to a hexadecimal string return v.toString(16); }); } var guid = createGuid(); console.log(guid);
This function will generate a GUID by utilizing a specific pattern containing placeholders for hexadecimal characters.
It will use the replace
method along with a regular expression to replace each ‘x’ and ‘y’ placeholder with randomly generated hexadecimal digits.
The resulting GUID will then be stored in the variable guid
and logged to the console.
Output:
b2c115a1-ff2e-41b5-9765-3bb1924521f3
Browser-Specific Approaches
In a browser environment, if you cannot or prefer not to use NPM packages, then you can try the approaches mentioned below.
- Utilize the
crypto.getRandomValues()
method available in modern browsers. - Use a CDN to include the UUID library.
Now, explain the above methods one by one to get the GUID/UUID.
Using crypto.getRandomValues()
Modern browsers provide the crypto
object with a method getRandomValues()
that can be used to generate cryptographically strong random values. This can be utilized to create UUIDs.
Example
function generateUUID() { // Creates a new Uint8Array with 16 bytes to store the UUID var arr = new Uint8Array(16); // Fills the array with random values using the crypto.getRandomValues method window.crypto.getRandomValues(arr); // Sets the version number of the UUID (bits 12-15 of the 7th byte) to 4 arr[6] = arr[6] & 0x0f | 0x40; // Version 4 UUID // Sets the variant of the UUID (bits 6-7 of the 9th byte) to 10xx arr[8] = arr[8] & 0x3f | 0x80; // Variant 10xx // Converts the array of bytes to an array of hexadecimal strings var hexArr = Array.from(arr, function(byte) { // Converts each byte to a two-character hexadecimal string return ('0' + byte.toString(16)).slice(-2); }); // Joins the hexadecimal strings and formats the UUID with hyphens return hexArr.join('').match(/.{1,8}-?.{1,4}-?.{1,4}-?.{1,4}-?.{1,12}/).join('-'); }
This function will generate a Version 4 UUID (randomly generated). It used crypto.getRandomValues() to get an array of 16 random bytes and then format them into a valid UUID string.
Use a CDN to include the UUID library.
If you’re working in a browser environment and can’t use NPM for package management, but still want the reliability of a well-tested library, you can include a UUID library via a CDN (Content Delivery Network). This is especially useful if you need more advanced UUID functionality or different versions of UUIDs.
Below is an example using the uuid
library via CDN.
Include the uuid
library in your HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/uuid/8.3.0/uuid.min.js"></script>
Generate a UUID in your JavaScript code
var uuid = uuidv4(); console.log(uuid);
This script tag will load the uuid
library from a CDN, and you’ll be able to use uuidv4()
function to generate UUIDs.