I am trying to pare 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
.
I am trying to pare 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
.
String
constructor are objects and objects cannot be pared in JS. The last two are created as object and then overwritten by String, so it works.
– Tushar
Commented
Dec 22, 2015 at 5:23
new String
instances, are pared by their identity and that's different for every new
instance created. So, 2 distinct object can never be equal. Primitives, as you're using the 2nd example (the objects are replaced, not modified), are pared by their values.
– Jonathan Lonowski
Commented
Dec 22, 2015 at 5:29
When 2 objects(For eg, objects created using new String()) are pared 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 parison is done by the value
and not the reference. Which is why u==t
returns true
, as mentioned in the ments.
Where the first parison is paring 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 paring references where the second is actually paring values. If you want to apre the first example by value, you would pare the value of the String object like so.
u.valueOf() === t.valueOf();
You are creating new objects with new String()
and referred to MDN's Comparison operators :
If both operands are objects, then JavaScript pares internal references which are equal when operands refer to the same object in memory.
When using the new String
constructor you're creating objects rather than strings. So when you pare them, they are not equal.
var t = new String("testing");
typeof t;
// "object"
var u = "testing";
typeof u;
// "string"
t == u
// false
However, if you pared their string values:
t.toString() == u.toString()
// true
they would be.
Basically in first case you creating object. so paring to object do a ===
so its always return false
.
in second case you doing the same thing in first two line with empty string.
var u=new String();
var t=new String();
use console.dir(u)
to see.
but in bottom line u='test';t='test';
you overwrite u,t values by string primitive values. so its just paring value of test