Clue Mediator

How to generate a Unique ID in JavaScript

📅January 15, 2022

In this article, we will show you how to generate a unique ID in JavaScript. There are several ways to generate a unique identifier using JavaScript.

Checkout more articles on JavaScript

Method 1:

function uuidv4() {
  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);
  });
}

console.log(uuidv4());
// Output: b9eac503-fe73-49a7-a19c-e469aa255c92

Method 2:

function uuid() {
  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);
  });
}

console.log(uuid());
// Output: 852e9a4f-616d-45a4-8fe4-9dc37afcf482

Method 3:

const uid = function(){
  return Date.now().toString(36) + Math.random().toString(36).substr(2);
}

console.log(uid());
// Output: kyg0z26npc43wq7vaa

That’s it for today.
Thank you for reading. Happy Coding..!! 🙂