4

Why does the creation of a string object not return true when compared strictly to a primitive string value?

var obj = new String('0');
var str = '0';

console.log(obj == str); //returns true
console.log(obj === str); //returns false
onTheInternet
  • 6,421
  • 10
  • 41
  • 74
  • 4
    Do a `typeof` on each variable. The first is an `object`. The second is a `string`. –  Jul 11 '17 at 13:36
  • 1
    It might help to also read the difference between the identity === operator and the equality operator == as stated in https://stackoverflow.com/questions/359494/which-equals-operator-vs-should-be-used-in-javascript-comparisons and quite a few other SE posts. – scrappedcola Jul 11 '17 at 13:42

3 Answers3

9

As obj type is object where str is string, Hence obj === str is false.

var obj = new String('0');
var str = '0';

console.log(typeof obj);
console.log(typeof str);
Satpal
  • 132,252
  • 13
  • 159
  • 168
0
console.log(obj == str); //returns true
console.log(obj === str); //returns false

Identity and equals operators is quite different things. Second case is very simple, because object can't be identical to string. First case evolves boxing/unboxing mechanism, and result value is dependent on operator in expression. In this example, because str is primitive, obj will be unboxed, and comparation will success.

Expression new String('xxx') == new String('xxx') , of course, will be false, because there is no primitive value to force convert to it's type. See https://www.w3schools.com/js/js_type_conversion.asp for details.

Vladislav Ihost
  • 2,127
  • 11
  • 26
0

String Object and String type value are are not the same that is why '===' gives false

If you are making a string object, it is different than a string type value.

var obj = new String('0'); // this is object type
var str = '0';             // this is string type value

when you use '===' that is strict equality,

Strict equality compares two values for equality. Neither value is implicitly converted to some other value before being compared. If the values have different types, the values are considered unequal. Read More

That's why when you use '==='(strictly compare) it returns false

Check this answer to see difference between string object and string type value, Difference between the javascript String Type and String Object

Lahar Shah
  • 7,032
  • 4
  • 31
  • 39