0

I have a variable defined as:

var o = new String("0");

In console when i write:

o === o

it returns true but when i write:

new String("0") === new String("0")

it returns false

I don't understand why is it working on variable references but not on objects?

I tried it as:

(new String("0")) === (new String("0"))

because the problem may arise due to operator precedence, but it still returns false

Shiran Abbasi
  • 89
  • 1
  • 2
  • 7
  • 1
    it works exacly on objects by checking the identity. – Nina Scholz Mar 23 '19 at 12:25
  • Yes it returns false, To strict equality you need to compare two exact values as far i know. Use it on console, it returns true. new String("0").value === new String("0").value; – Robin Mar 23 '19 at 12:28
  • 2
    @Robin strict equality has nothing to do with this example. Strict equality just means that it would fail if the two values are not of the correct types, loose equality works for `0 == "0"` - a strng and a number that still express the same data when converted. The issue is that two *different* objects are always *different*, hence why the equality fails. `==` or `===` doesn't check their contents but if they are literally one and the same object instance. – VLAZ Mar 23 '19 at 12:35
  • @VLAZ yes i understand. When you use == it compares the value, not type. But when you use === it compares both the value and type. Is it right ? By the way '@js_tut' tweets about this yesterday and explain clearly. – Robin Mar 23 '19 at 15:23

1 Answers1

0
 new String("0") === new String("0")

Here you are comparing two different Strings having different references. Thats why you are getting false.

 o === o

Here, You are actually comparing the same string (reference is same in this case).

Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151