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
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);
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With