Categories
JavaScript Answers

How to create unique ID with JavaScript?

Spread the love

Sometimes, we want to create unique ID with JavaScript.

In this article, we’ll look at how to create unique ID with JavaScript.

How to create unique ID with JavaScript?

To create unique ID with JavaScript, we can use the Math.random method.

For instance, we write

const id = Math.random().toString(16).slice(2);

to call the Math.random method to return a random number between 0 and 1.

Then we call toString with 16 on the returned number to convert it to a hex string.

Next, we call slice with 2 to return the string from index 2 to the end of it.

Conclusion

To create unique ID with JavaScript, we can use the Math.random method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *