I'm going through and assignment from eloquent JS book, and I'm super confused! The point is to compare 2 objects.
What's going on here:
!deepEqual(a[key], b[key])
? Why do I need to run the recursion on the object values?Why
a.key
andb.key
break the code?If I remove the
if (a === b) return true;
line - the code breaks? I thought I'm dong the deep comparison.
function deepEqual(a, b) {
if (a === b) return true;
if (a == null || typeof a != "object" ||
b == null || typeof b != "object") return false;
let keysA = Object.keys(a), keysB = Object.keys(b);
if (keysA.length != keysB.length) return false;
for (let key of keysA) {
if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
}
return true;
}
let 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