Question on JavaScript Object Equality Exercise

I have a question about video “17- Exercise 3- Object Equality” in " The Ultimate JavaScript Mastery Series - Part 1" course.

Mosh’s textbook answer for the areEqual function is:

let address1 = new Address('a', 'b', 'c');
let address2 = new Address('a', 'b', 'c');

function areEqual(address1, address2) {
	return address1.street === address2.street && === address2.street && 
	address1.zipCode === address2.zipCode;

In contrast, I wrote:

function areEqual(address1, address2) {
    for (let key in address1)
        if (address1[key] !== address2[key])
            return false;

    return true;

My code appears to work, and seems cleaner and more extensible than Mosh’s answer. Is there anything wrong with my solution that I should consider?


I’d say your solution is fine for comparing two Address objects. Note that your solution would also compare functions if our Address object had any. And think of what would happen if we passed in an empty object or a number for address1. The function would return true.

Thanks, that’s a good reminder to consider the edge cases!

I also used the same for in loop and this is better approach from avoiding repitition of 3 && operators.

i think we can use the if statement before applying for in loop in these conditions, because with for in loop there is also benefit of testing if we dont know the name of object properties i.e. street, city and zipcode.