Generating Unique ID using JavaScript

Getting along with generating unique ID in JavaScript is an almost required in the majority of applications. In today’s time with the advent of Single Page Applications, this has become a standard approach which maintaining the state as well as multiple other stuff. So let’s see a simple javascript function which will help us to generate unique ID in JavaScript.

Let’s see the code below

The above approach makes use to the ES6 for convenience, crypto API and a bit of clever logic. What has been done is, it returns v4 Unique Identifier UUID for the format  xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx  where each  x is replaced with a random Hexadecimal digit from 0 to f and y is being replaced by a random Hexadecimal digit ranging from 8 to b. As you can see while generating unique id, ES6 adds the syntactic sugar around the crypto API. Go ahead and use this in your upcoming projects. Let us know what all wrappers you have written across this. We will be glad to know your views.

 


Also published on Medium.

Join our 2500+ fellow readers

Join our 2500+ fellow readers

Joining our mailing list will for sure keep you at the top of Web Development Ecosystem. Connect with us and also other fellow developers.

You have Successfully Subscribed!

Pin It on Pinterest

Share This