Learn how to generate random unique id in javascript.
Javascript does not have any inbuilt method to generate unique ids, but it does a have method called Math.random()
which generates a unique number every time called.
We can use this to generate unique random ids.
The random id generated will be string based and we will generate the alpha-numeric string based on the random number we will get from the Math.random()
.
We will create a function which will be generating a string of length 4
.
let s4 = () => { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } console.log(s4()); //282b
The toString()
method converts the number to given string format. Here we are converting it to a Hexadecimal format.
Now we will the above function and call it recursively to generate the random unique id. Calling it recursively will help us deciding the length and the order of the unique id.
//generates random id; let guid = () => { let s4 = () => { return Math.floor((1 + Math.random()) * 0x10000) .toString(16) .substring(1); } //return id of format 'aaaaaaaa'-'aaaa'-'aaaa'-'aaaa'-'aaaaaaaaaaaa' return s4() + s4() + '-' + s4() + '-' + s4() + '-' + s4() + '-' + s4() + s4() + s4(); } console.log(guid()); //"c2181edf-041b-0a61-3651-79d671fa3db7"
We can now use this function wherever we want as a unique random id generator in javascript.