Computer >> Computer tutorials >  >> Programming >> Javascript

How to Create GUID / UUID in JavaScript?


We can create GUID or UUID in JavaScript using the following methods −

Math.Random() function

To create or generate UUID or GUID in javascript use the following code with Math.Random() function

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

Note − This should not be used in production as GUID or UUID generated by Math.Random() may not be unique.

npm uuid module

We can use npm's uuid module for generation of RFC4122 UUIDS. First install it using −

$ npm install uuid

Then create a js file(script.js) with the following contents −

const uuid = require('uuid')
console.log(uuid())
console.log(uuid())
console.log(uuid())

You can run it using the following command −

node script.js

Examples of created UUIDs −

a85a8e6b-348b-4011-a1ec-1e78e9620782
03ea49f8-1d96-4cd0-b279-0684e3eec3a9
7289708e-b17a-477c-8a77-9ab575c4b4d8