Swipe left or right to navigate to next or previous post

Generated UUID using Javascript

18 Aug 2023 . category: JavaScript . Comments
#JavaScript #Tools

 Generated UUID using Javascript - Tapan BK

Need of generating the UUID

When working with the data in database, it's a common practice to add some kind of unique primary key to provide a unique identifier for each row in a table. Imagine a user table, we won't want to use the name,address or date of birth as the unique identifier for a user as some user may share common name, address or even date of birth. Instead, it's a good to assign truly unique identifier as auto increment number or the UUID.

What is UUID?

A UUID (Universally Unique IDentifier) is a 36 character alphanumeric string that can be uniquely identify the record. UUID id usually identify rows of data within a database table with each row assigned a unique UUID.

Here is the example of UUID:
adce071d-9d5c-4f0d-9d7a-162854c10432.

Syntax:

The basic syntax of a GUID/UUID is as follows: xxxxxxxx-xxxx-Mxxx-Nxxx-xxxxxxxxxxxx

Where:
  • x – represents a hexadecimal digit (0-9, A-F).
  • M – represents the version of the GUID/UUID (1-5).
  • N – represents the variant of the GUID/UUID (8, 9, A, or B).

UUID are not only unique to the database table and it is highly likely to be unique globally which means that row's UUID unique to our database table but with anu row with UUID in any system around the world. The UUID has 340,282,366,920,938,463,463,374,607,431,768,211,456 different possible UUIDs which results in very less chances of being duplicate with other.

Advantage of UUID

  • They are globally unique and it has very less chances of being duplicate
  • It can be generated without the need to check against the central node. The UUID can be generated anynomously without being worried about the duplication

DisAdvantage of UUID

  • It takes 128bits of memory. It may not be suitable when the storage is limited

Could not get the uuid

Ways to generate the UUID

1. Using JavaScript Math.random function

    const random_uuid = uuidv4();
    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);
        });
    }

2. Using the uuid npm package

    const { v4: uuidv4 } = require('uuid');
    const random_uuid = uuidv4();
or
    import { v4 as uuidv4 } from 'uuid';
    const newGUID = uuidv4();

Tapan B.K. | Full Stack Software Engineer

Tapan B.K. is Full Stack Software Engineer. In his spare time, Tapan likes to watch movies, visit new places.