hikinthru hikinthru - 1 year ago 53
Javascript Question

Javascript Deep Comparison

Questions about deep comparison of objects have been asked, and I have the solution. But there is a line in the solution that I don't completely understand.

This is the solution, it is a question in Ch 4 of Eloquent JS to compare objects. I get all of it except the line:

if (!(prop in a) || !deepEqual(a[prop], b[prop]))

It is found toward the bottom. Here is full function:

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;

Is "if (!(prop in a)" comparing the existence of a property in 'b' at that index, or is it comparing values?

Really the same q. about the second half, but I know it's a different answer: what type of comparison is "!deepEqual(a[prop], b[prop])" making (e.g., true or false)? I understand the recursion, but as in my previous question, is this making an 'it exists' comparison, or a comparison of the information in the values?

Thank you in advance.


According to MDN:

The in operator returns true if the specified property is in the specified object.


The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

So to answer your first question, prop in a is checking whether prop, a field from object b, exists in object a.

To answer your second question, deepEqual(a[prop], b[prop]) is checking whether the object a[prop] and b[prop] are equal including all its children and contents.