DEV Community

Cover image for Generating Universally Unique Identifiers (UUIDs) in JavaScript: A Comprehensive Guide with Code Examples
Odumosu Matthew
Odumosu Matthew

Posted on

Generating Universally Unique Identifiers (UUIDs) in JavaScript: A Comprehensive Guide with Code Examples

In JavaScript, you can generate UUIDs using the uuid package. Here's a step-by-step guide:

Step 1: Install the uuid package:
You need to install the uuid package to generate UUIDs. You can use npm (Node Package Manager) to do this.

npm install uuid

Enter fullscreen mode Exit fullscreen mode

Step 2: Import the uuid module:
In your JavaScript file, import the uuid module.

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

Enter fullscreen mode Exit fullscreen mode

In this line, we're using object destructuring to import the v4method as uuidv4. The v4method is used to generate version 4 UUIDs, which are random and widely used.

Step 3: Generate a UUID:
You can now generate a UUIDusing the uuidv4() method.

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

Enter fullscreen mode Exit fullscreen mode

Here, myUUIDwill hold a newly generated UUID, and we're logging it to the console.

The Complete JavaScript Code:

Here's the complete JavaScript code to generate a UUID:

// Step 1: Install the uuid package if you haven't already.
// npm install uuid

// Step 2: Import the uuid module.
const { v4: uuidv4 } = require('uuid');

// Step 3: Generate a UUID.
const myUUID = uuidv4();
console.log(myUUID);

Enter fullscreen mode Exit fullscreen mode

This code imports the uuidpackage, generates a UUIDusing the uuidv4() method, and then logs the generated UUIDto the console.

By following these steps, you can easily generate UUIDsin JavaScriptfor your applications. These UUIDsare unique and can be used in various contexts, such as database records, APIendpoints, or as identifiers for various objects in your code.

LinkedIn Account : LinkedIn
Twitter Account: Twitter
Credit: Graphics sourced from DevOps Zones

Top comments (0)