0

The code below will return an object:

alert(typeof new String("my string"));

but it will return string when new is removed:

alert(typeof String("my string"));

Why is that?

5 Answers5

2

From MDN:

String literals (denoted by double or single quotes) and strings returned from String calls in a non-constructor context (i.e., without using the new keyword) are primitive strings.

When called without new, it returns a string primitive which has type "string" in Javascript. With new it returns a String object.

In most cases they're interchangeable, for example if you access a property of a string primitive it is automatically converted to a String object.

Paul
  • 139,544
  • 27
  • 275
  • 264
1

String is a constructor function to create instances of the String(which is an object).

The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

More about new here

and calling those constructor function with out new, is like casting ,

so even if you call String(1);
you will get "1" (typeof is string here(primitive type) )

Oxi
  • 2,918
  • 17
  • 28
0

The "new" keyword invokes the String class, meaning you have just created a new String object, which is why your code returns object. Without the new, you are simply converting your inner object to a String. (See http://www.w3schools.com/js/js_type_conversion.asp for more info on type conversions)

perennial_
  • 1,798
  • 2
  • 26
  • 41
0

String("my string") is going to typecast the value inside it to string, while new String("my string") is going to return a new object due new operator.

New operator will invoke constructor of Object type (String in this case) and create an instance of this object.

gurvinder372
  • 66,980
  • 10
  • 72
  • 94
0

String literals like "something" and String("something") are considered primitive types. However, when using the new keyword, a reference to that string is created like an object. You can get around this problem by using the instanceof keyword. For example:

var something = new String("something");

if ((typeof something === "string") || (something instanceof String))
    console.log("Its a string!");
William Callahan
  • 630
  • 7
  • 20