If you want to compare age (and generally do any operations with the value of properties) - make it easier:
let man = { name: 'Sergey', surname: 'Sergeev', age: 30, valueOf() { return this.age; } } let man2 = { name: 'Ivan', surname: 'Ivanov', age: 30, valueOf() { return this.age; } } console.log(man.age === man2.age);
Below is an explanation
The valueOf () method returns the primitive value of the specified object.
JavaScript calls the valueOf method to convert an object to a primitive value. You rarely need to call the valueOf method yourself; JavaScript automatically calls it when an object is detected, when a primitive value is expected .
The fact is that when you perform primitive operations >, <, +, -, *, / with objects, the initial value of each object is returned for each object at that moment - in your case, what you have redefined in the valueOf methods. And operations are already extinguished with the returned values.
When you perform operations ==, === on objects, object references are compared.
But if you do this: when one of the operands has a primitive value, then the object will also be transformed into a primitive (when there is no strict altitude):
let man = { name: 'Sergey', surname: 'Sergeev', age: 30, valueOf() { return this.age; } } let man2 = { name: 'Ivan', surname: 'Ivanov', age: 30, valueOf() { return this.age; } } console.log(man === 30); // false, потому что сравниваются ссылки на объекты (=== — строгое сравнение) console.log(man == 30); // true, потому что для man вернется примитивное значение
Two “identical” even empty objects will never be equal, because objects will always compare links
console.log({} == {}); console.log({} === {});
But if the variables pointing to the same object are compared (they have the same reference), then true will be returned
var obj1 = {}; obj1.foo = 100; var obj2 = obj1; obj2.biz = 200; obj1.bar = { text: 'bar' }; console.log(obj1 == obj2); console.log(obj1 === obj2);
Additional information on type conversion for primitives and object conversion:
valueOfmethod, albeit implicitly in his code, at that time I would recommend using the properties ofman.ageandman2.ageobjects for thisman2.age... - Alexander Bragin