Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Deep Comparison

Tags:

javascript

Questions about deep comparison of objects have been asked, and I have the solution. But there is a line in the solution that I don't completely understand.

This is the solution, it is a question in Ch 4 of Eloquent JS to compare objects. I get all of it except the line:

    if (!(prop in a) || !deepEqual(a[prop], b[prop]))

It is found toward the bottom. Here is full function:

function deepEqual(a, b) {
  if (a === b) return true;

  if (a == null || typeof a != "object" ||
      b == null || typeof b != "object")
    return false;

  var propsInA = 0, propsInB = 0;

  for (var prop in a)
    propsInA += 1;

  for (var prop in b) {
    propsInB += 1;
    if (!(prop in a) || !deepEqual(a[prop], b[prop]))
      return false;
  }

  return propsInA == propsInB;
}

Is if (!(prop in a) comparing the existence of a property in 'b' at that index, or is it comparing values?

Really the same q. about the second half, but I know it's a different answer: what type of comparison is !deepEqual(a[prop], b[prop]) making (e.g., true or false)? I understand the recursion, but as in my previous question, is this making an 'it exists' comparison, or a comparison of the information in the values?

Thank you in advance.

like image 438
hikinthru Avatar asked Jun 23 '26 15:06

hikinthru


1 Answers

According to MDN:

The in operator returns true if the specified property is in the specified object.

Also:

The for...in statement iterates over the enumerable properties of an object, in arbitrary order. For each distinct property, statements can be executed.

So to answer your first question, prop in a is checking whether prop, a field from object b, exists in object a.

To answer your second question, deepEqual(a[prop], b[prop]) is checking whether the object a[prop] and b[prop] are equal including all its children and contents.

like image 86
0xcaff Avatar answered Jun 26 '26 05:06

0xcaff



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!