This content originally appeared on DEV Community and was authored by Maria Antonella ?
Last week, I needed to find a way to generate a 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;
}
? 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! :)
This content originally appeared on DEV Community and was authored by Maria Antonella ?

Maria Antonella ? | Sciencx (2021-09-15T17:27:49+00:00) Making random and unique ID with Javascript. Retrieved from https://www.scien.cx/2021/09/15/making-random-and-unique-id-with-javascript/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.