2

On many sites, I have read that for example these two are different:

var s1 = String('s1');     // typeof s1 == 'string'
var s2 = new String('s2'); // typeof s2 == 'object'

The same applies on booleans, numbers, etc.

However, I did not find any useful information on WHY these two constructs produce different kind of objects. Is there any specific reason for that? Are there any cases when I would leverage both approaches?

2
  • stackoverflow.com/questions/3080655/… Commented Jul 12, 2013 at 9:12
  • There are basically no common cases to use the new operator with String(), Number() or Boolean(). Commented Jul 12, 2013 at 9:13

3 Answers 3

3
var s1 = String('s1');

Calls the function String which returns a string primitive.

var s2 = new String('s2');

Calls String as a constructor which returns an object, that is an instance of String.

String knows when it's called in a non-constructor context. The creator of the language has deliberately decided not to return an object in that case.

The only useful purpose I can imagine for the first example is type conversion, like String(4), which creates '4'. But there are other ways to achieve this.

There does not seem to be a good use case for the second example. Directly creating a wrapper object can even be harmful when the code expects a primitive. E.g.:

var s2 = new String('s2');
doSomethingUseful(s2);

function doSomethingUseful(aParameter) {
  if (typeof aParameter === 'string') { //s2 isn't
Sign up to request clarification or add additional context in comments.

3 Comments

When would you recommend using new?
@nnnnnn never ;) Directly using wrapper objects doesn't make much sense. Do you think that this should be part of the answer?
Well, it would be more complete given that you did suggest a purpose for the version without new. (Though using Number() in a similar way is a more likely scenario than using String().)
1

Here's a mini FAQ for you.

Why are there String and Number objects?

Primitive values, like "foobar" or 123 cannot have properties and methods, so there must be objects that actually hold these.

How String and Number objects are used?

They're used implicitly by the engine itself. Every time you assess a property of a primitive, the engine creates a new implicit object just for this (this is called "autoboxing") . For example x = "foobar".length is turned into this:

 temp = new String("foobar")
 x = temp.length
 delete temp

Can I use String and Number objects in my own code?

You can, but hardly need. Due to automatic boxing, you can call all objects' props and methods directly on primitive values. Also, primitives and boxed objects behave differently under some circumstances, e.g. if(x)... vs. if(new String(x))....

What are String() and Number() functions?

These are constructors for String and Number objects. Additionally, when called directly, without new, they perform type conversion, i.e. return a new primitive (not object) of their respective type. In pseudocode, the logic behind String is like this:

function String(primitiveValue) {
     primitiveString = convert_to_string(primitiveValue)
     if called with new
         return new StringObject(primitiveString)
     else
         return primitiveString

Reference: http://es5.github.io/#x15.5.1

Are direct calls to String() and Number() useful?

Yes! Every time a type casting is required you want to use these. Some people prefer hacks, like +x instead of Number(x) or x+"" instead of String(x), but explicit casting looks cleaner.

Why typeof new String() is object and not string?

Everything created by the means of new is an object, no matter which specific constructor is used.

3 Comments

Thanks @thg435 for exhausting FAQ. Just one more question - Is there a reason why new String() returns an object of type 'object'? Instead, I would naturally expect to return new object of type 'string'.
@PavelLobodinský: no, "string" is a primitive type, all objects are of type "object".
I see. I am confusing typeof with Java's instanceof. Thanks for explanation, now it makes much more sense - everything whose typeof != 'object' is a primitive type.
0

Well String(), Function() or Boolean() are all objects of Function reference type.

Before discussing the question u should know there are two data types in javascript.
1)Primitive -for simple string,number,undefined,null,object values etc. cantaining variables.They can be differentiated by typeof operator.For object this will only tell if the given variable contains reference type of data and not what kind of reference type.
2)reference types-they are just like classes in other oop languages.They are the types of objects that can be created by javascript.Some Examples are-function,Date,regex,primitive Wrapper Type etc.They can be differentiated by instanceof operator.

Primitive wrapper Types-The are actually the objects that contain the primitive values but they behave like objects passing their values by reference.They are created by calling the constructor functions with new operator.Ex- String-They are objects containing String kind of Values.Syntax for creating these objects

var str=new String("s2")

here str behaves as an object.

typeof(str)=="object"

Whereas just calling String() is just any calling any ordinary function whose only purpose is to convert any other primitive value into string.

var s1 = String('s1');     // typeof s1 == 'string'

I hope I was clear.If you have any doubts then ask them

5 Comments

"They are created by calling the constructor functions" - Just calling a function does not create an object ^^
Yes, "They are created by calling the constructor functions."
Buddy as in example we need to use new operator to create an instance of object by calling Constructor function.I also wrote this-Whereas just calling String() is just any calling any ordinary function whose only purpose is to convert any other primitive value into string.
Well, then you should write "They are created by calling the constructor functions with the new operator".
I forgot buddy but I wrote in example. I am writing it now. You win.

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.