2

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?

1

4 Answers 4

2

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 );
Sign up to request clarification or add additional context in comments.

Comments

1

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

i dont know using square brackets as the array constructor is accepted over new Array(), it just easer :}
0

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

eww, don't like to w3schools bro
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.