If I remember correctly, String() called w ithout a new operator is a type conversion
function that returns a primitive string.
Professor: That’s true, altho ugh it doesn’t really matter whether number is a string
primitive or object. Whenever you use a property or method on a string primitive, a
temporary String object called a wrapper object is c reated automatically behin d the
scenes. When you stop usin g the object’s properties and methods, the wrapper object
is destroyed. This effectively blurs the distinc tion between primitive and object string
types and you can use a primitive string as though it was an object:
var s = "I am primitive";
console.log(s.length); //Writes 14
console.log(s[3]); //Writes m
console.log(s.slice(0, 4)); //Writes I am
Still, th ere is an important difference between primitive strings and object strings.
Consider the next code fragment:
var strObject1 = new String("Something");
var strObject2 = new String("Something");
console.log(strObject1 == strObject2);
console.log(strObject1 == "Something");
What do you think the result will be?
Maria: I remember that objects are compared b y reference. In th e above example we
compare objects that have equal values but are distinct. Both compar iso ns therefore
return false.
Professor: The first comparison indeed returns false. Th e second comparison, how-
ever, has a primitive string on one of its sides. Because of tha t, the string object
strObject1 on its other side is converted to a primitive string and both primitives are
compared by value, wh ic h returns true.
The same object-to-primitive conversions take place when yo u compare string objects
using greater-than or less-than operators. Let me summarize the rules for you:
• If both operands of the equality operator (==) are string obje cts, then the opera-
tor returns true if and only if both operands refer to one and the same object. If
they refer to different objects, the return value is fa lse even when both objects
hold iden tical strings. No object-to-primitive conversion occurs here.
• If one operand of the equa lity ope rator (==) is a primitive string and the other is
an ob je ct string, then the object is converted to a primitive before comparison.
Both primitives ar e then compared by value.
• If either operand of a comparison operator >, <, >=, or <= is a string object,
then that object is converted to a string primitive. The string primitives are then
compared alphabetically.
9.5. S tring Object 183