Explain equality of objects in JavaScript.

JavascriptWeb DevelopmentObject Oriented Programming

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 −


 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>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>
   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";


The above code will produce the following output −

On clicking the ‘CLICK HERE’ button −

Published on 18-Jul-2020 12:15:28