Deep comparison of two objects

Hello Campers,

Can anyone explain me how the solution for deep comparison of two objects works?

Here is the full solution:

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;
}

The part that I cannot understand is:

  for (let key of keysA) {
    if (!keysB.includes(key) || !deepEqual(a[key], b[key])) return false;
  }

I will appreciate any help.

It is a recursion. Try to find another simple decision. It is complecate to debug and explain.

Hi, thanks. I know it is recursion.

What I cannot understand is the flow of the code.

1 Like
!deepEqual(a[key], b[key])) return false;

the function returns opposite of the boolean. It depends. If it is true, returns false and otherwise.Simple checks for both object has other children since both objects has equal size.

Thanks! I’ve reviewed the code. Tested it using console.log() to better understand the output and seems like for now it’s clear :slight_smile:

1 Like