What is shallow comparison in Js?

Hi, a shallow comparison happen if 2 values are equals in case of primitive types (is data that is not an object and has no methods) like:  string, number, bigint, boolean, undefined, and symbol. But in case of object it just check the reference and not the values inside that object. 

Then examples will show us how to compare 2 objects and see if they are equals or not.

Example 1:

// Object 1
let objectA = {
  propertyOne: 30,
  propertyTwo: 10
};

// Object 2
let objectB = {
  propertyOne: 30,
  propertyTwo: 10
};

// Matching the reference of the 2 objects
objectA = objectB;

// Object.is() This function returns true if they have the same 
// reference and false if they do not.
console.log('Are equal? -->',  Object.is(objectA, objectB));

Result: This will be a shallow comparison as I mentioned in case of object it just check the reference

Example 2:

// Object 1
let objectA = {
  propertyTwo: 30,
  propertyOne: 10
};

// Object 2
let objectB = {
  propertyOne: 30,
  propertyTwo: 10
};

//  JSON.stringify() Convert a JavaScript object into a string
console.log('Are equal? -->', JSON.stringify(objectA) === JSON.stringify(objectB));

Result: This is a quick solution to compare if 2 objects have the same key value, the order of the properties in every object is important because if the properties are equal but the order is different then the result will be false and this is because is comparing 2 string and if the 2 strings are equals then will be true otherwise will be false.

Example 3

Other solution is use a library called Lodash this library help us to work with arrays, objects, & strings.

Example 4

// Object 1
let objectA = {
  propertyOne: 30,
  propertyTwo: 50
};

// Object 2
let objectB = {
  propertyOne: 30,
  propertyTwo: 50
};

const compareObjects = (objectA, objectB) => {
  // ['prop1', 'prop2', 'etc']
  let aProperties = Object.getOwnPropertyNames(objectA); 
  // ['prop1', 'prop2', 'etc']
  let bProperties = Object.getOwnPropertyNames(objectB);

  // Checking the properties array length
  // If the quantity of the properties are not equal
  if (aProperties.length !== bProperties.length) { 
    return false; // then the objects are not equals
  }

  // Go through every position in the array
  for (let i = 0; i < aProperties.length; i++) {
    // getting the prop name in that position of the array 
    let propName  = aProperties[i]; 

    // Comparing the object values 30, 50
    if (objectA[propName] !== objectB[propName]) {
      return false;
    }
  }

  return true;
}

console.log('Are equal? -->', compareObjects(objectA, objectB));

Result: In this case we are comparing if the objects have the same properties and if they have the same values.

By Cristina Rojas.