Making random ID with Javascript

Maria Antonella 🦋 - Sep 15 '21 - - Dev Community

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

. . . . . . . . . . . . . . . . . .
Terabox Video Player