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
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
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);
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.
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