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
According to MDN:
The in operator returns
trueif the specified property is in the specified object.
Also:
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.
The in operator returns true if the object on the right of the expression contains a key with the value of the string on the left of the expression.
Eg: prop in a is true if a contains a key with the same name as the string value of prop. Eg:
var prop = "age";
var obj1 = {
name: "Dave",
age: 21,
record: { ... }
};
var obj2 = {
name: "John",
record: { ... }
};
console.log(prop in obj1); // true
console.log(prop in obj2); // false
If prop was set to "record" then deepEqual(a[prop], b[prop]) recursively compares the values in a.record and b.record.
It's checking for existence. It says: "For each property in B, examine A. If A doesn't have the property, or if the value of the property on A doesn't deeply equal the value of the property on B, return false".
An alternate implementation would avoid the existence check on that line, and instead use if (typeof A == 'undefined') at the top of the function to validate the input parameters at the beginning of each round of recursion...at a glance, I think that'd be equivalent, but less efficient. The current implementation avoids the invocation on the undefined property.