Last Updated: September 09, 2019
·
4.443K
· kevincennis

Random alphanumeric strings in JS

Sometimes in larger JS apps, I'll need a way to generate unique IDs for a large number of objects.

The following is a nice one-liner for that purpose:

Math.random().toString(36).slice(2)

To add a bit more entropy, you can use:

+new Date() + Math.random().toString(36).slice(2)

2 Responses
Add your response

Perhaps you meant:

(Math.random()+ +new Date).toString(36).replace('.','')
over 1 year ago ·

Nope, I meant what I posted.

The reason for including the date first is to reduce the (admittedly very low) likelihood of collisions between the random strings.

By prefixing the date, you reduce the risk of duplication -- because the colliding hashes would have to have been generated within a millisecond of eachother to actually cause a problem.

over 1 year ago ·