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?
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?
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.
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.
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) )
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)
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.
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!");