JavaScript

Generate a unique ID in Javascript

In this tutorial, we are going to see how to generate a unique ID. JavaScript does not have a built-in method for generating unique identifiers, but you can use a method called Math.random() which generates a unique alphanumeric string on each call.
 

How to Generate a unique ID in Javascript
<!DOCTYPE html>
<html>
   <body>
      <p>Click on the button to generate a unique ID.</p>
      <button onclick="generate()">Click here</button>
      <p id="uniqueID"></p>
      <script>
         function generate() {
         let id = () => {
           return Math.floor((1 + Math.random()) * 0x10000)
               .toString(16)
               .substring(1);
         }
           document.getElementById("uniqueID").innerHTML = id();
         }
      </script>
   </body>
</html>
Result

Click on the button to generate a unique ID.



mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

One thought on “Generate a unique ID in Javascript

  • This is not unique.
    Let us not confuse unique with random!

    Reply

Leave a Reply

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