Search code examples
javascripttypescriptequalitydeep-diff

Why do you need deep object comparison?


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?


Solution

  • 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'
      }
    }