A random number is not the same as a unique number. There is absolutely no guarantee of uniqueness in a collection of randomly generated numbers.
DateTime.Now() will also not generate a unique number, unless guaranteed not to run at the exact same millisecond. for quite a while now, computers are fast enough to run a few iteration of a loop within a single millisecond.
I am a WordPress/PHP/JS developer, working as a web engineer for a proptech company in Dublin, Ireland. I have my side projects and I like to experiment with various web technologies.
Depending on the application, this is the right way to do it. In my case, I don't have a loop, I have several elements being displayed on subsequent clicks, and there's several seconds between each click. So there's zero chances of an identical ID.
While yes it's theoretically possible for UUID to produce a duplicate, it is statistically improbable (read: impossible) to do so, even when striving for such and taking into account the birthday paradox. According to wikipedia:
"Only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. Or, to put it another way, the probability of one duplicate would be about 50% if every person on earth owned 600 million UUIDs." en.wikipedia.org/wiki/Universally_...
You actually more likely to have a totally unique ID than to have gotten one that anyone has ever seen in the entire world! And it will be this way until the sun runs out of juice.
UUID is the only one that should be used. Date.now() is terrible for reasons that Zohar mentions.
We can test it by adding generated to a map and comparing size:
constsize=1000000constset=newSet(newArray(size).fill(0).map(()=>uid()))console.log(size===set.size?'all ids are unique':`not unique records ${size-set.size}`)
Hi, I'm Sujal, and I'm a frontend developer with a strong interest in JavaScript and React. I've been working in the field for over 4.5 years and have developed a passion for it.
For anyone trying out the first example with uuid, it works just fine and the module respects the standards, it just evolved and I guess the post did not 😅.
Anyhow here's the correct implementation
import{v4asuuidv4}from'uuid';uuidv4();// ⇨ '9b1deb4d-3b7d-4bad-9bdd-2b0d7b3dcb6d'// ... or using CommonJS syntax:const{v4:uuidv4}=require('uuid');uuidv4();// ⇨ '1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed'
It's my way to generate a 100% guaranted unique and random local id:
varMyLib={//Max id guaranted to be unique will be 999 999 999. //Add more zeros to increase the value.lastUid:100000000,generateUid:function(){this.lastUid++;//Way to get a random int value betwen min and max: //Math.floor(Math.random() * (max - min) ) + min;varrandValue=Math.floor(Math.random()*(99999-10000))+10000;returnNumber(this.lastUid.toString()+randValue);}};console.log(MyLib.generateUid());
Math.random does neither generate truly random numbers nor are they unique. Its randomness is of course based on the range you provide and that is its own shortcoming. The other methdos you mentioned are a lot more unique and more random.
Cheers!
🧠 AwwyNO | Software Engineer | Clean Code == Clean Conscience
Python| Django | JavaScript | Bash| React| C
I believe in strong backend architecture, smart frontends, and doing things the right way.
Location
Kenya
Education
Bsc. Forensic Science and Software Engineering (ALX)
how about using crypto.randomUUID(), which is part of the Web Crypto API that generates a UUIDv4. I read that it is fast, secure, and simple to use. Here is an example: const uuid = crypto.randomUUID();
console.log (uuid); // a random and unique ID.
Hi! I'm Rohan, a Full Stack Software Engineer, with a background of working with Deep Learning and AI, who loves to use his skills to create products that are at the intersection of all of these!
I was building a local db with npmjs.com/package/lowdb just for testing purposes and the Date.now() is more than enough to get an unique id. Thanks Rahman :)
The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.
A random number is not the same as a unique number. There is absolutely no guarantee of uniqueness in a collection of randomly generated numbers.
DateTime.Now()will also not generate a unique number, unless guaranteed not to run at the exact same millisecond. for quite a while now, computers are fast enough to run a few iteration of a loop within a single millisecond.You could decrease the chances by using multiple of the author's ways:
Maybe
function uniqueID() {
return Math.floor(Math.random() * Date.now())
}
You could even string multiple randoms together:
Math.floor(Math.random() * Math.floor(Math.random() * Date.now()))
Depending on the application, this is the right way to do it. In my case, I don't have a loop, I have several elements being displayed on subsequent clicks, and there's several seconds between each click. So there's zero chances of an identical ID.
thank you, this work also. to also include string i use Math.floor(Math.random() * Date.now()).toString(16)
While yes it's theoretically possible for UUID to produce a duplicate, it is statistically improbable (read: impossible) to do so, even when striving for such and taking into account the birthday paradox. According to wikipedia:
"Only after generating 1 billion UUIDs every second for the next 100 years, the probability of creating just one duplicate would be about 50%. Or, to put it another way, the probability of one duplicate would be about 50% if every person on earth owned 600 million UUIDs."
en.wikipedia.org/wiki/Universally_...
You actually more likely to have a totally unique ID than to have gotten one that anyone has ever seen in the entire world! And it will be this way until the sun runs out of juice.
UUID is the only one that should be used. Date.now() is terrible for reasons that Zohar mentions.
I kind of agree 🤔
I think the title should be "how to generate random id"
But, at least I put UUID as the most recommended approach
I was researching this and while I agree uuid package is probably least human error prone, it does mean potentially adding another package.
It seems like utilizing
Date.now().toStringor perhapsnew Date().getTime()or similar and alsoMath.randomcould do the trick:We can test it by adding generated to a map and comparing size:
__
Your script now are in my personal helpers file. thanks.
This is the best comment here, and with only one like! A perfect small utility and a way to test it, all super intuitive and functional : )
There is 1 inbuilt method which returns randomUUID
window.crypto.randomUUID()No 3rd party library, Super fast ⌛
For anyone trying out the first example with uuid, it works just fine and the module respects the standards, it just evolved and I guess the post did not 😅.
Anyhow here's the correct implementation
Feel free to test it out ^^
i never think of using millisecond to generate an id, nice approach!
greetings from indonesia :)
It's my way to generate a 100% guaranted unique and random local id:
Math.random does neither generate truly random numbers nor are they unique. Its randomness is of course based on the range you provide and that is its own shortcoming. The other methdos you mentioned are a lot more unique and more random.
Cheers!
how about using crypto.randomUUID(), which is part of the Web Crypto API that generates a UUIDv4. I read that it is fast, secure, and simple to use. Here is an example:
const uuid = crypto.randomUUID();console.log (uuid); // a random and unique ID.
What a great read!
🔥
Check my article related to uuid in JavaScript
dev.to/pranay_rauthu/uuid-in-javas...
Wow, great article 🤩
I was building a local db with npmjs.com/package/lowdb just for testing purposes and the Date.now() is more than enough to get an unique id. Thanks Rahman :)
The Math.random() static method returns a floating-point, pseudo-random number that's greater than or equal to 0 and less than 1, with approximately uniform distribution over that range — which you can then scale to your desired range. The implementation selects the initial seed to the random number generation algorithm; it cannot be chosen or reset by the user.
developer.mozilla.org/en-US/docs/W...
Thanks, this is useful
Date.now works for my simple use case, thank you
nice! Date.now() good resolve
I think UUID as the most recommended approach