Reputation: 1213
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.
Upvotes: 1
Views: 100
Reputation: 700910
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 String
conversion function, which will just return the string primitive unchanged.
The String
conversion function is usually used to turn other things into string primitives, for example a number:
var s = String(42);
To create a String
object you use the new
keyword:
var s = new String("hi there.");
The String
object has all the methods that you are used to use on a string, like the length
property. The reason that you can use them on string primitives also, is that they are automatically converted to String
objects when you use a method on them.
So, this:
var l = "asdf".length;
actually does the same as:
var l = new String("asdf").length;
The String
conversion function always returns a string primitive, so if you have a String
object, the function will turn it back into a string primitive:
var s = "asdf"; // typeof s returns "string"
var s = new String(s); // typeof s now returns "object"
s = String(s); // typeof s now returns "string"
Upvotes: 3
Reputation: 352
I never heard those names before, but 'constructor notation' would most likely be the q2Var2 one, since you're passing arguments to the constructor of String. It's not really important how you call them though, is it? :P
Upvotes: 0