DEV Community

Cover image for Making random ID with Javascript
Maria Antonella 🦋
Maria Antonella 🦋

Posted on

Making random ID with Javascript

Last week, I needed to find a way to generate a random and unique id to get names for phone files on ios systems. Anyway, googling around, I found this simple function.

All you have to do is call it, where you need to generate the id, and pass the desired length of the id.
And magic! It returns an id made with characters and numbers (in this example, of course!)

const makeRandomId= (length) => {
      let result = ''
      const characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789'
      for (let i = 0; i < length; i++ ) {
        result += characters.charAt(Math.floor(Math.random() * characters.length));
     }
     return result;
  }

Enter fullscreen mode Exit fullscreen mode

👉 charAt: The charAt() method returns the character at a specified index in a string.
👉 floor(): The floor() method rounds a number DOWNWARDS to the nearest integer, and returns the result.
👉 random(): Math.random() returns a random number between 0 (inclusive), and characters.length (exclusive):

Math.random() used with Math.floor() can be used to return random integers.

That's all! :)

Discussion (14)

Collapse
miketalbot profile image
Mike Talbot • Edited on

If length is long enough then this is likely to produce non-conflicting ids for many cases on a single system, the problem is that they are not cryptographically secure. Conflicts become more likely when it is used on multiple systems.

The reason that they aren't secure is that Math.random() is predictable and not "really random". In fact, producing one ID with this method, of reasonable length, would probably give enough information to work out what the next ID was going to be.

This is a problem if you used such an ID as the key to a database record and then exposed that ID in a URL, because a hacker would be able to work out many other IDs and potentially access data they shouldn't.

To create really secure IDs then some "entropy" should be added - this is something that you could derive from the system or the environment. Like the movement of the users mouse, the number of packets received on the server. Something that is not computer generated if possible. You should also make the random part of the calculation come from a cryptographically secure method. There are many with different characteristics, for instance the mersenne twister is considered good, there are many way of getting that algorithm including this.

Collapse
meatboy profile image
Meat Boy

Exactly. Problem with generating some "random and unique" string may sounds trivial, but it's not. As addition to what you have wrote, the problem is tried to be solved by ietf and uuid implementations: ietf.org/rfc/rfc4122.txt

Collapse
miketalbot profile image
Mike Talbot

Personally I use nanoid which is ideal for many circumstances, has variable length and is faster that uuid

Collapse
pengeszikra profile image
Peter Vivo

maybe this one liner help (toString(32) means radix: 32):

(37e16 * Math.random() + 37e16).toString(32)
Enter fullscreen mode Exit fullscreen mode

result is random text with lead a -> k other character small letters and numbers.

const uid = () => (37e16 * Math.random() + 37e16).toString(32)
Array(3).fill().map(uid).sort().join('-')
// 'bo0bp82gqsi0-cjkdo45jtau0-hfllk7fgot00'
Enter fullscreen mode Exit fullscreen mode
Collapse
ayoubmehd profile image
Ayoub

You can use this package to create a UUID npmjs.com/package/uuid it works in browsers and Node.
Your solution will not create a unique random string.

Collapse
zachjonesnoel profile image
Jones Zachariah Noel

+1

Collapse
artidata profile image
Imaduddin Haetami

Well, this will be random but not unique. Kudos.

Collapse
david_brear_dc8676f75b6d4 profile image
David Brear

As a proof-of-concept or coding challenge, this is okay but DO NOT DO THIS IN A PRODUCTION ENVIRONMENT!!!! If you need random, unique IDs use uuid packages from npm. There’s a saying “don’t reinvent the wheel” especially when your “wheel” is a less-good version.

For production systems don’t: roll your own encryption, roll your own auth (unless you REALLY REALLY REALLY know what you’re doing), roll your own ID generation.

If you do any of the above YOU WILL BE HACKED.

Collapse
sanampakuwal profile image
Sanam

Best solution:
Date.now(); // parse this as string

Collapse
lionelrowe profile image
lionel-rowe • Edited on

Nope, that's a really bad solution.

class User {
    constructor(name) {
        this.name = name
        this.id = String(Date.now())
    }
}

const alice = new User('Alice')
const bob = new User('Bob')

alice.id === bob.id // true
Enter fullscreen mode Exit fullscreen mode
Collapse
obaino82 profile image
Obaino82

Well done

Collapse
ats1999 profile image
Rahul kumar

If this is not so frequent, you can use date.now()

Collapse
sqlrob profile image
Robert Myers

Things are not frequent until they are. If you ever expect to scale, don't even start this way.

Plus it's guessable.

Collapse
lassev05 profile image
LasseV

thanks, good post