0

I'm going through and assignment from eloquent JS book, and I'm super confused! The point is to compare 2 objects.

  1. What's going on here: !deepEqual(a[key], b[key]) ? Why do I need to run the recursion on the object values?

  2. Why a.key and b.key break the code?

  3. 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
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
Russell
  • 1
  • 1
  • If you didn’t recuse it wouldn’tbe deep. “obj.key” looks for a property named “key”, “obj[key]” looks for a property named whatever the *value* of “key” is. If you remove the “===“ you’re removing all checks for equality, which is the whole point of the function. – Dave Newton May 09 '22 at 17:49
  • JS objects are compared by reference, try `{} == {}` in your console and you'll get false. So to compare two objects, you need to verify (recursively in this case) that they have the same structure no matter how deep in you go, and on each leaf, you make sure the values are actually the same (by using `if (a === b) return true;`). – M0nst3R May 09 '22 at 17:57
  • Also, `object.thing` expects a key called "thing" to be present in the object `object`, whereas doing: `const thing = "other"; object[thing]` expects a key called "other" to be present in the object. – M0nst3R May 09 '22 at 18:01

0 Answers0