On Firebug:
>>> str1 = String('String One');
"String One"
typeof(str1);
"string"
>>> str2 = new String('String Two');
String { 0="S", 1="t", 2="r", more...}
typeof(str2);
"object"
My Question is what is the difference between both technique?
What is the advantage of one over the other?
-
1Have a look at developer.mozilla.org/en/JavaScript/Reference/Global_Objects/….Rob W– Rob W2011年11月21日 18:32:30 +00:00Commented Nov 21, 2011 at 18:32
4 Answers 4
The only real difference is that using new String(), you get an object that extends from Object, meaning that this code works:
var foo = new String( 'bar' );
foo.property = 42;
whereas this doesn't:
var foo = 'bar';
foo.property = 42;
It's also sometimes useful if you need to get a string:
var foo = new String( 21*2 );
Comments
There really isn't much of an advantage one way or the other because almost nobody creates a string this way they just declare var a = 'This is a string'; This is similar to the fact that the accepted way to create an array is not var a = new Array() but var a = []. I guess the first way might have an advantage because it labeled as a string instead of an object, but
var a = 'This is a string';
typeof(a);//returns string
1 Comment
accepted over new Array(), it just easer :}in the first example you got the return type of String();
in the second you got the type of String() itself / or more precisely the type of the new String() instance.
more info:
http://www.w3schools.com/jsref/jsref_String.asp
http://www.w3schools.com/jsref/jsref_obj_string.asp
1 Comment
The new String wrapper is a wart put into the language a long time ago to please the Java folks. As you might have already noticed, those inconsistencies are good reasons why it is not a widely recommended practice today.
Meanwhile, using String(something) is useful if you want to convert values to strings but most people just use the shorter ''+something instead.
String('string') is unecessary, since 'string' already is a string.
tldr avoid new String and other wrappers like new Array and new Number like the plague.