I was checking in my console. When i checked empty object directly like {} == {}
, it show false.
Why it's showing false
? shouldn't it show true
as both are equal ?
I was checking in my console. When i checked empty object directly like {} == {}
, it show false.
Why it's showing false
? shouldn't it show true
as both are equal ?
When i checked empty object directly like {} == {} , it show false.
You have two different objects here and not one. Here ==
checks whether the given two objects are same or not.
Scenario 1:
var foo = {}; //new object
var bar = foo; //shared same object
foo == bar;// true
Scenario 2:
var foo = {}; //new object
var bar = {}; //new object
foo == bar;// false
If you still wish to compare two different objects, try this:
var foo = {}; //new object
var bar = {}; //new object
JSON.stringify(foo) == JSON.stringify(bar);// true
Here, JSON.stringify({})
gives string value "{}"
Primitives like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference. That comparison by reference basically checks to see if the objects given refer to the same location in memory, which they do not, so the comparison is false.