1

Image

Why empty object is not equal to empty object in JavaScript? (Array too)

const value = {} == {}; // false
Yousaf
  • 27,861
  • 6
  • 44
  • 69
Sherzod
  • 33
  • 3
  • 5
    They reside in different places in memory – Taplar Jul 03 '20 at 17:42
  • 3
    No two distinct objects are ever equal to each other. – Pointy Jul 03 '20 at 17:43
  • Objects are compared by their identity or their reference instead of the values inside them. Since two empty objects are 2 separate objects in memory, they are not equal. Arrays are objects in javascript, so same rules apply to them as well. – Yousaf Jul 03 '20 at 17:46
  • This is part of the language definition – MikeB Jul 03 '20 at 17:46
  • From my experience with languages like C and Java, this is typically the case. In those languages if you want to know if an object is the same as another you have to write your own toString overload or a hashing method and then compare those two. But in general two objects are not equal if they are not actually the same object in memory. – Taplar Jul 03 '20 at 17:46

1 Answers1

-1

Here is a quick explanation of why

{} == {}; // false

[] == []; // false

works like that in JavaScript.


From MDN Web Docs - Working with objects: Comparing objects.

In JavaScript, objects are a reference type. Two distinct objects are never equal, even if they have the same properties. Only comparing the same object reference with itself yields true.

// Two variables, two distinct objects with the same properties
var fruit = {name: 'apple'};
var fruitbear = {name: 'apple'};

fruit == fruitbear; // return false
fruit === fruitbear; // return false
// Two variables, a single object
var fruit = {name: 'apple'};
var fruitbear = fruit;  // Assign fruit object reference to fruitbear

// Here fruit and fruitbear are pointing to same object
fruit == fruitbear; // return true
fruit === fruitbear; // return true

fruit.name = 'grape';
console.log(fruitbear); // output: { name: "grape" }, instead of { name: "apple" }

For more information about comparison operators, see Comparison operators.


From Eloquent Javascript Book - Data Structures: Objects and Arrays

Arrays, then, are just a kind of object specialized for storing sequences of things. If you evaluate typeof [], it produces "object".

Marian13
  • 7,740
  • 2
  • 47
  • 51
  • The reason is that because both variables have different memory locations that's why they are not equal. – Mudassir Sep 23 '21 at 06:45