Why empty object is not equal to empty object in JavaScript? (Array too)
const value = {} == {}; // false
Why empty object is not equal to empty object in JavaScript? (Array too)
const value = {} == {}; // false
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".