Comparing objects in JavaScript: why {} !== {} and how to compare correctly?
Hi everyone! I just started learning JavaScript and encountered a confusing situation. I'm trying to compare two objects that look exactly the same, but I get false.
Here's my code:
```javascript
const user1 = { name: 'Anna', age: 25 };
const user2 = { name: 'Anna', age: 25 };
console.log(user1 === user2); // false
console.log(user1 == user2); // also false
```
I expected it to be true, because the properties and their values match! But JavaScript says they are different. Why does this happen?
I understand that for numbers and strings this works fine:
```javascript
console.log(5 === 5); // true
console.log('hello' === 'hello'); // true
```
But with objects — it doesn't. I tried comparing via JSON.stringify:
```javascript
console.log(JSON.stringify(user1) === JSON.s
No answers yet.
Log in to leave an answer
Blogs