Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Javascript's Math.random() generate a unique number which will not repeat in future?

Tags:

javascript

I need a random number which I will be storing in the database per record and that (the generated random number)too should not repeat in future. So is Math.random() function is good for that?

Thanks in advance

like image 448
KT B Avatar asked Oct 21 '25 13:10

KT B


2 Answers

Random is random and statistically it will repeat somewhere in the future. What you can do is combine something unique with a random part - for example use the unix timestamp with a random number.

function getRand(){
    return new Date().getTime().toString() + Math.floor(Math.random()*1000000);
}
like image 165
Dropout Avatar answered Oct 24 '25 03:10

Dropout


Math.random() will not give you a unique number, in general it will not even give you a real random number.

You can try to use a datetime-based random algorythm, or go for a random number and then check if it's already in your database, but both approaches are not 100% save. There is pretty much only one way to ensure the number you store is unique, which is on database level.

like image 23
Ninigi Avatar answered Oct 24 '25 04:10

Ninigi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!