Skip to content

JavaScript object equality | Code

  • by

You can’t check object equality directly same as strings and numbers do in JavaScript. If two objects have the same properties and all of their properties have the same value, they would be considered equal. Let’s take a look and see what happens.

var obj1= {
    occupation: "Bounty Hunter",
    genetics: "superb"
};

var obj2= {
    occupation: "Bounty Hunter",
    genetics: "superb"
};

console.log(obj1 === obj2);// false

Output is false because primitives data types like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference.

JavaScript object equality

A simple example code comparison by reference basically checks to see if the objects given refer to the same location in memory.

<!DOCTYPE html>
<html>
<body>
  <script>
    var obj1 = {
      occupation: "Bounty Hunter",
      genetics: "superb"
    };

    var obj2 = {
      occupation: "Bounty Hunter",
      genetics: "superb"
    };

    var obj3 = obj1;

    console.log(obj1 === obj2);
    console.log(obj1 === obj3);
  </script>
</body>
</html>

Output:

JavaScript object equality

Objects have the same value

To check the instance you can use === equality, but to match the value you need to work more.

let name = {
firstName: "suprabha",
lastName: "supi"
}let fullName = {
firstName: "suprabha",
lastName: "supi"
}function isEqual(obj1, obj2) {
var props1 = Object.getOwnPropertyNames(obj1);
var props2 = Object.getOwnPropertyNames(obj2); if (props1.length != props2.length) {
return false;
} for (var i = 0; i < props1.length; i++) {
let val1 = obj1[props1[i]];
let val2 = obj2[props1[i]];
let isObjects = isObject(val1) && isObject(val2); if (isObjects && !isEqual(val1, val2) || !isObjects && val1 !== val2) {
return false;
}
}
return true;
}function isObject(object) {
return object != null && typeof object === 'object';
}console.log(isEqual(name, fullName)); // true

You can also use the Lodash library for an easy approach: https://lodash.com/docs/4.17.15#isEqual

Do comment if you have any doubts or suggestions on this JS equality topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Your email address will not be published. Required fields are marked *