Javascript Check Object Equality

Published on : August 03,2022
Javascript Check Object Equality

Hi dev,

In this article we will learn example about Check Object Equality using javascript. Let's start …

 

Syntax & Example: object-equality.html

<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>object-equality</title>
  <link rel="stylesheet" type="text/css" href="../style.css" />
</head>

<body>

  <h1>25-object-equality!</h1>

  <h3>Write function to check object equality</h3>

  <script type="text/javascript" src="script.js"></script>

</body>

</html>

 

Syntax & Example: script.js

console.log('25-object-equality');

// Constructor function/method - pascalCasing - pascal notation - use this keyword
function Student(name, age, rank, country) {
  this.name = name;
  this.age = age;
  this.rank = rank;
  this.country = country;
}

let Students1 = new Student('Dinanath', 35, 5, 'India');
console.log('Students1', Students1);

let Students2 = new Student('Dinanath', 35, 5, 'India');
console.log('Students2', Students2);

console.log('----------');

// Objects are reference type, objects can have same properties but they are from different memeory location, they can be equal if both objects have same properties
function isObjectEqual(obj1, obj2){
  return obj1.name === obj2.name &&
         obj1.age === obj2.age &&
         obj1.rank === obj2.rank &&
         obj1.country === obj2.country
}

console.log('isEqual', isObjectEqual(Students1, Students2));

console.log('----------');

// Objects are same if both are pointed to same object
function isObjectPointSame(obj1, obj2){
  return obj1 === obj2;
}

let isSame1 = isObjectPointSame(Students1, Students2);
console.log('isSame1', isSame1);

let Students3 = Students2;
let isSame2 = isObjectPointSame(Students2, Students3);
console.log('isSame2', isSame2);

 

Hope it can help you…

Categories : JavaScript

Tags : HTML

Praful Sangani
Praful Sangani
I'm a passionate full-stack developer with expertise in PHP, Laravel, Angular, React Js, Vue, Node, Javascript, JQuery, Codeigniter, and Bootstrap. I enjoy sharing my knowledge by writing tutorials and providing tips to others in the industry. I prioritize consistency and hard work, and I always aim to improve my skills to keep up with the latest advancements. As the owner of Open Code Solution, I'm committed to providing high-quality services to help clients achieve their business goals.


0 Comments

Leave a comment

We'll never share your email with anyone else. Required fields are marked *

Related Articles

How to download a file in JavaScript
Praful Sangani By Praful Sangani - July 25,2022
How to swapping variables in javascript
Praful Sangani By Praful Sangani - August 03,2022
JavaScript exercise-examples for Beginners
Praful Sangani By Praful Sangani - August 03,2022