-5

What is the reason for the following code resulting to false?

{} === {}
//false

what is the reason for this code turning true?

 var obj = {};
 obj === obj
  //true

plz answer in a simple and concise language

Maizere Pathak.Nepal
  • 2,383
  • 3
  • 27
  • 41

5 Answers5

4

Comparisons of objects don't check if the objects have the same content, they check if they are the same object. Each {} creates a new object. Your first test tests to see if a new object is the same object as a different new object. Your second test compares the created object to itself.

From the the documentation for comparison operators:

An expression comparing Objects is only true if the operands reference the same Object

Or, from the language specification:

Step 7: Return true if x and y refer to the same object. Otherwise, return false.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
1

In the first case, you are creating two objects and comparing them. In the second case you are comparing the same object.

Julien Grenier
  • 3,364
  • 2
  • 30
  • 43
0

When you do {} you're creating an (empty) object literal (a new object with no properties). When you're doing

{} === {}

you're comparing two entirely different objects, so it returns false.

However, when you do:

var obj = {};
obj === obj

you're comparing the same object, so it returns true.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
0

In second you are comparing an object with itself that is very logic to be equal.

At first you are not comparing the same things, you try to compare things that show the same.

Mhche
  • 143
  • 14
0

{} creates a new object.

=== checks that they are actually the same object. Although they are both new empty objects, they are actually different empty objects.

To see why this matters, try this:

var a = {};
var b = {};
var c = a;
a.key = 'value';
console.log(b);
console.log(c);

You will see that because a and b are different empty objects, changing a doesn't change b. Because c is actually the same empty object as a, putting something into a also puts it into c.

Eric
  • 3,142
  • 17
  • 14