Objects in JavaScript are compared by reference, not by content. Operators == and === return true only if both operands refer to the same object in memory. Even if objects look the same, they are not equal if they are different objects.
In JavaScript, objects are not compared like primitive values. It’s important to understand how comparison works to avoid errors.
Objects are compared by reference, not by value:
const obj1 = { name: 'John' };
const obj2 = { name: 'John' };
console.log(obj1 == obj2); // false
console.log(obj1 === obj2); // falseconst obj1 = { a: 1 };
const obj2 = { a: 1 };
// obj1 and obj2 are different objects in memory
console.log(obj1 === obj2); // falseconst obj1 = { a: 1 };
const obj2 = obj1; // Same reference
console.log(obj1 === obj2); // trueconst user1 = { name: 'John', age: 25 };
const user2 = { name: 'John', age: 25 };
// Even with same data — not equal
console.log(user1 === user2); // falseconst user = { name: 'John' };
const sameUser = user; // Same reference
console.log(user === sameUser); // true
console.log(user === { name: 'John' }); // falseconst obj1 = { a: 1 };
const obj2 = { a: 1 };
// With objects == and === work the same
console.log(obj1 == obj2); // false
console.log(obj1 === obj2); // falseconst obj = { a: 1 };
console.log(obj == null); // false
console.log(obj === null); // false
console.log(obj == undefined); // false
console.log(obj === undefined); // falseconst user = { name: 'John' };
const admin = user; // Same reference
console.log(user === admin); // true
admin.name = 'Peter';
console.log(user.name); // 'Peter' — it's the same objectlet obj1 = { a: 1 };
let obj2 = obj1;
console.log(obj1 === obj2); // true
obj2 = { a: 1 }; // New object
console.log(obj1 === obj2); // false// ❌ Thinking objects with same data are equal
const obj1 = { name: 'John' };
const obj2 = { name: 'John' };
if (obj1 === obj2) {
console.log('Equal'); // Won't trigger
}
// ✅ Proper understanding
console.log(obj1 === obj2); // false// ❌ Comparing object with primitive
const obj = { toString() { return 'test'; } };
console.log(obj == 'test'); // true (conversion)
console.log(obj === 'test'); // false (different types)Understanding object comparison helps avoid errors when working with data and conditions in code.
Want more articles to prepare for interviews? Subscribe to EasyAdvice, bookmark the site and improve yourself every day 💪