How to create a unique ID for each object in JavaScript?

Following is the code to create a unique ID for each object −


 Live Demo

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
<h1>Create a unique ID for each object</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button&g;
<h3>Click on the above button to check if id generated are unique or not</h3>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let obj = {
      id: Symbol("UID"),
      a: 22,
      b: 44,
   let obj1 = {
      id: Symbol("UID"),
      a: 12,
      b: 41,
   BtnEle.addEventListener("click", () => {
      if ( === {
         resEle.innerHTML = "The id generated are not unique <br>";
      else {
         resEle.innerHTML = "The id generated is unique for each object";


The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

Updated on: 21-Jul-2020


Kickstart Your Career

Get certified by completing the course

Get Started