 Muntasir Alam -4 years ago 125
Javascript Question

# Comparing two objects to see if equal

currently I am following a book and am severely confused and have tried understandng the following code several times. My first confusion is actually approaching the problem of comparing two objects a, and b.

`````` function deepEqual(a, b) {
if (a === b) return true;

if (a == null || typeof a != "object" ||
b == null || typeof b != "object")
return false;

var propsInA = 0, propsInB = 0;

for (var prop in a)
propsInA += 1;

for (var prop in b) {
propsInB += 1;
if (!(prop in a) || !deepEqual(a[prop], b[prop]))
return false;
}

return propsInA == propsInB;
}

var obj = {here: {is: "an"}, object: 2};
console.log(deepEqual(obj, obj));
// → true
console.log(deepEqual(obj, {here: 1, object: 2}));
// → false
console.log(deepEqual(obj, {here: {is: "an"}, object: 2}));
// → true
`````` Frxstrem
Answer Source
``````function deepEqual(a, b) {
if (a === b) return true;
``````

First, we're checking if `a` and `b` are strictly equal (meaning, "referring to exactly the same thing"). Most things, such as strings and numbers, will pass this test if they are equal; objects are the exception, since two "identical" objects may not necessarily be the same object (they can just look the same).

``````  if (a == null || typeof a != "object" ||
b == null || typeof b != "object")
return false;
``````

Then we're saying that if either of the two is not an object, and they did not pass the last test, then they cannot be the same. Again, objects are the exception here, so the remaining code will take care of the case where `a` and `b` are both objects.

``````  var propsInA = 0, propsInB = 0;

for (var prop in a)
propsInA += 1;
``````

This code simply counts the number of properties of `a`.

``````  for (var prop in b) {
propsInB += 1;
if (!(prop in a) || !deepEqual(a[prop], b[prop]))
return false;
}
``````

This code takes every property in `b`, and checks that `a` contains the same property with the same value. If `a` doesn't have a property that `b` has, or they are different, then the two objects cannot be equal.

``````  return propsInA == propsInB;
}
``````

Finally, if `a` and `b` do not have the same number of properties, then they cannot be equal. However, if they do have the same number of properties, then `a` and `b` must be equal, since `a` has all the properties that `b` has, and only those.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download
Latest added