0

The following code from EJS demonstrates that two objects with the same properties are not necessarily the same 'value'. So I'm wondering what values the equality operator actually uses when comparing two objects. From looking around I can see it is a 'reference'. But what is this reference? Is it a memory address?

let object1 = {value: 10};
let object2 = object1;
let object3 = {value: 10};

console.log(object1 == object2);
// → true
console.log(object1 == object3);
// → false
cham
  • 8,666
  • 9
  • 48
  • 69

3 Answers3

3

Yes, but you have no access to memory because this is a memory managed language.

(Clarification: It does not have to be, references can be implemented differently.)

H.B.
  • 166,899
  • 29
  • 327
  • 400
2

If those values are non primitive, the comparison is by the reference in memory.

This is how the memory looks like according to your scenario:

      +-----------------+------------------+------------------+
      |     object1     |      object2     |     object3      |
      +-----------------+------------------+------------------+
      |                 |         |        |                  |
      |   {value: 10} <-----------+        |   {value: 10}    |
      |                 |                  |                  |    
      +-----------------+------------------+------------------+

So, object1 and object2 point to the same value and object3 to another value.

Equality operators

Equality (==)

The equality operator converts the operands if they are not of the same type, then applies strict comparison. If both operands are objects, then JavaScript compares internal references which are equal when operands refer to the same object in memory.

Community
  • 1
  • 1
Ele
  • 33,468
  • 7
  • 37
  • 75
0

in fact they are the same object, if you modify the value of the first, like this

object1.value = 5;

and then you consult the value of the second, you will see that it was also altered too

console.log(object2.value) // → 5

btw, if you have a cat named 'kitty' but your mom names him 'pillow paws',

kitty === pillow paws // -> true, it's the same cat

Eliseo
  • 604
  • 4
  • 10