Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript's string comparison

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.

like image 929
subi_speedrunner Avatar asked Sep 02 '25 04:09

subi_speedrunner


2 Answers

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.

like image 199
Bhargav Ponnapalli Avatar answered Sep 04 '25 22:09

Bhargav Ponnapalli


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();
like image 34
idream1nC0de Avatar answered Sep 04 '25 22:09

idream1nC0de