object.is() in equality comparison JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

The object.is() method introduced in ES6 as a way to compare two values. These two values can either be primitives or objects. It does a little better comparison than == and ===.

Following is the code for object.is() in equality comparison −

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: blueviolet;
   }
</style>
</head>
<body>
<h1>Object.is() equality comparsion</h1>
<div class="result"></div>
<button class="Btn">Click here</button>
<h3>Click on the above button to compare objects using Object.is()</h3>
<script>
   let resEle = document.querySelector(".result");
   let BtnEle = document.querySelector(".Btn");
   let obj = { a: 11, b: 22 };
   let obj1 = { a: 11, b: 22 };
   let obj2 = obj;
   BtnEle.addEventListener("click", () => {
      if (Object.is(obj, obj1)) {
         resEle.innerHTML = "obj = obj1";
      } else {
         resEle.innerHTML = "obj != obj1 <br>";
      }
      if (Object.is(obj, obj2)) {
         resEle.innerHTML += "obj = obj2";
      }
   });
</script>
</body>
</html>

Output

On clicking the ‘CLICK HERE’ button −


raja
Published on 17-Jul-2020 07:24:22
Advertisements