1

reference: https://dmitripavlutin.com/how-to-compare-objects-in-javascript/

Following to the reference, deep comparison is:

The deep equality is similar to the shallow equality, but with one difference. During the shallow check, if the compared properties are objects, a recursive shallow equality check is performed on these nested objects.

const objA = {
  propA: 123
  propB: 'a'
  propObj1: { // assume reference: 1234
     propObj1: 'abc'
  }
}

const objB = {
  propA: 123
  propB: 'a'
  propObj1: { // assume reference: 1234
     propObj1: 'abc'
  }
}

Is it possible for objA and objB to be equal in shallow comparison but not in deep comparison?

Because their propObj1 have the same reference, change to objA.propObj1 will be also reflected to objB.propObj1 which means they will also be equal in deep comparison. Can you give an example where it is true in shallow comparison but false in deep comparison?

Inigo
  • 12,186
  • 5
  • 41
  • 70
shapeless
  • 175
  • 1
  • 10
  • "_their `propObj1` have the same reference_", they don't, both the properties are independent objects in the memory. If you create `propObj1` in `objB` like this: `propObj1: objA.propObj1`, then they would refer the same object. – Teemu Dec 10 '21 at 07:01
  • 2
    It's *very* rare that you'd have what you describe here - two objects where the inner object property is shared. A lot of times this happens, it's because *it is a bug* - you've "cloned" the object but didn't realise it's a shallow clone. Yes, there are also cases where you *would* want the same object instead of a clone of it, however, that's rare. So, *in the scenario you describe* - no you don't need deep comparison. But 1. It's quite rare that you'd have it 2. You're also leaving out multiple nestings. Had you looked at *real* use-cases you wouldn't be asking this. – VLAZ Dec 10 '21 at 07:10

1 Answers1

2

You answered your own question! The very fact that you had to say "assume reference: 1234" in your example says that you know that a shallow compare will not work if propObj1 pointed to distinct but equal values (i.e. your exact example but without the "assume reference: 1234" comment.

objA and objB below will fail a shallow equals check, but pass a deep equals check:

const objA = {
  propA: 123
  propB: 'a'
  propObj1: {
     propObj1: 'abc'
  }
}

const objB = {
  propA: 123
  propB: 'a'
  propObj1: {
     propObj1: 'abc'
  }
}
Inigo
  • 12,186
  • 5
  • 41
  • 70