Watching a tutorial today I came across the following:
var q2Var1 = "hi there.",
q2Var2 = String( "another string here." );
Is q2Var the “constructor notation” and q2Var the “literal notation” for declaring a variable, or am I not drawing the correct conclusion?
Thank you.
No, neither of those use a constructor to create a string object.
The first is just a string primitive, the second is a string primitive that is sent through the
Stringconversion function, which will just return the string primitive unchanged.The
Stringconversion function is usually used to turn other things into string primitives, for example a number:To create a
Stringobject you use thenewkeyword:The
Stringobject has all the methods that you are used to use on a string, like thelengthproperty. The reason that you can use them on string primitives also, is that they are automatically converted toStringobjects when you use a method on them.So, this:
actually does the same as:
The
Stringconversion function always returns a string primitive, so if you have aStringobject, the function will turn it back into a string primitive: