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
  • 135,475
  • 25
  • 268
  • 257
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,832
  • 16
  • 27
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,647
  • 2
  • 23
  • 39
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
  • 64,240
  • 8
  • 67
  • 88
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
  • 620
  • 7
  • 19