Computer >> Computer tutorials >  >> Programming >> Javascript

Explain equality of objects in JavaScript.


In JavaScript the primitive like string, number, boolean etc are compared by their values while objects (native or custom) are compared by their reference. Comparing by reference means whether the two or more object point to same location in memory or not.

Following is the code to explain equality of objects in JavaScript −

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Document</title>
<style>
   body {
      font-family: "Segoe UI", Tahoma, Geneva, Verdana, sans-serif;
   }
   .result {
      font-size: 18px;
      font-weight: 500;
      color: rebeccapurple;
   }
</style>
</head>
<body>
<h1>Equality of objects in JavaScript</h1>
<div class="result"></div>
<button class="Btn">CLICK HERE</button>
<h3>Click the above button to compare objects</h3>
<script>
   let BtnEle = document.querySelector(".Btn");
   let resEle = document.querySelector(".result");
   let obj = {
      name: "Rohan",
      age: 21,
   };
   let obj1 = {
      name: "Rohan",
      age: 21,
   };
   let obj2 = obj;
   BtnEle.addEventListener("click", () => {
      if (obj != obj1) {
         resEle.innerHTML = "obj is not equal to obj1 <br>";
      }
      if (obj2 === obj) {
         resEle.innerHTML += "obj2 is equal to obj";
      }
   });
</script>
</body>
</html>

Output

The above code will produce the following output −

Explain equality of objects in JavaScript.

On clicking the ‘CLICK HERE’ button −

Explain equality of objects in JavaScript.