I am trying to compare using the following below formats :
var u=new String('test');
var t=new String('test');
When i check (u==t) or (u===t)
it returns false
.
Similarly if I try to do
var u=new String();
var t=new String();
u='test';t='test';
Now (u==t) and (u===t)
returns true
.
When 2 objects(For eg, objects created using new String()) are compared using ==
, behind the scenes ===
is used.
Which makes
u == t
equivalent to
u === t
And since they are 2 different objects, the result is always false.
However, when you use a string literal, you are creating primitive data, and their comparison is done by the value
and not the reference. Which is why u==t
returns true
, as mentioned in the comments.
Where the first comparison is comparing object references using the String constructor, the second example you are reinitializing the u and t values to String literals. The first one is actually comparing references where the second is actually comparing values. If you want to comapre the first example by value, you would compare the value of the String object like so.
u.valueOf() === t.valueOf();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With