0

I have a quick question on why my function is returning false, when I expect it to be returning true.

function isEquivalent(a, b) {
    // arrays of property names
    var aProps = Object.getOwnPropertyNames(a);
    var bProps = Object.getOwnPropertyNames(b);

    // If their property lengths are different, they're different objects 
    if (aProps.length != bProps.length) {
        return false;
    }

    for (var i = 0; i < aProps.length; i++) {
        var propName = aProps[i];

        // If the values of the property are different, not equal
        if (a[propName] !== b[propName]) {
            return false;
        }
    }

    // If everything matched, correct
    return true;
}

var obj1 = {'prop1': 'test','prop2': function (){} };
var obj2 = {'prop1': 'test','prop2': function (){} };

isEquivalent(obj1,obj2); // returns false

the two objects(obj1, obj2) are perfectly matched but Why is return value false?

Could someone help me perfectly understand this function?

Alpaca
  • 148
  • 3
  • 8

1 Answers1

1

It's because the values of prop2 are two different functions (with the same body)

Try this instead and you'll see that if you use the same function as the value it will pass:

var func = function () {};
var obj1 = {'prop1': 'test','prop2': func };
var obj2 = {'prop1': 'test','prop2': func };

isEquivalent(obj1,obj2); // returns false

Functions are considered objects and follow the same equality rules

coagmano
  • 5,542
  • 1
  • 28
  • 41