DEV Community

Cover image for Making random ID with Javascript
Maria Antonella πŸ¦‹
Maria Antonella πŸ¦‹

Posted on

23 1

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! :)

Hostinger image

Get n8n VPS hosting 3x cheaper than a cloud solution

Get fast, easy, secure n8n VPS hosting from $4.99/mo at Hostinger. Automate any workflow using a pre-installed n8n application and no-code customization.

Start now

Top comments (14)

Collapse
 
miketalbot profile image
Mike Talbot ⭐ β€’ β€’ Edited

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
 
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
 
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
 
artidataio profile image
Imaduddin Haetami β€’

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

Collapse
 
sanampakuwal profile image
Sanam β€’

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

Collapse
 
lionelrowe profile image
lionel-rowe β€’ β€’ Edited

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
 
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
 
obaino82 profile image
Obaino82 β€’

Well done

Collapse
 
latze profile image
latze β€’

thanks, good post

SurveyJS custom survey software

JavaScript UI Libraries for Surveys and Forms

SurveyJS lets you build a JSON-based form management system that integrates with any backend, giving you full control over your data and no user limits. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more.

Learn more

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay