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

 Live Demo

<!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 −

On clicking the ‘CLICK HERE’ button −

Updated on: 18-Jul-2020

82 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements