JavaScript String Constructor Property String.constructor Property

This JavaScript tutorial introduces the constructor property for JavaScript string objects. The constructor property points to the function that created the object in question: in the case of strings (a native JavaScript data type), the constructor is the string constructor, called with "new String()".

What is the JavaScript String Constructor Property?

The constructor property is available to all JavaScript objects; it points to the ultimate function called to create the object type, without concerns for the way in which the object was created. For example, a JavaScript string can be created with the new String() constructor, the square-bracketed literal notation, or indirectly returned from a method like String.split(). Either way, the string generated has the same constructor.

var carter = new String();
alert( carter.constructor.toString() );

The above script returns a string representation of the object constructor (a string, in our case). The output varies from one JavaScript interpreter to another (depends on your browser's rendering engine); here is a sample: JavaScript string constructor property

Using Constructors to Check Object Data Types

The constructor property can also be used to check an object's data type (much like the "typeof()" operator). Below, we declare both a string and an array, and check if their constructor is the string constructor: in other words, whether or not the string constructor was used to create the object.

var carter = new String();
alert( carter.constructor === String );

Executing this script confirms (true) or denies (false) that our object is an string: JavaScript string constructor property

The JavaScript code below would return false, because our array's constructor is not the String constructor (it is the Array constructor).

var arlene = new Array();
alert( arlene.constructor === String );

Constructor for Custom JavaScript Objects

As illustration, here is a custom JavaScript object; a custom function serves as constructor (it assigns properties and methods to any new instance of the given object, a "ScriptingLanguage" in our case).

function ScriptingLanguage(a,b) { = a;
    this.syntaxType = b;

var js = new ScriptingLanguage("JavaScript","C");
alert( js.constructor.toString() );

The last line of our script generates the following, a string representation of our "ScriptingLanguage" constructor function: JavaScript object constructor

Test the String Constructor Property

Interactively test the string constructor property by editing the JavaScript code below and clicking the Test String Constructor Property button.

Browser support for JavaScript string constructor property
Internet Explorer supports the JavaScript string constructor propertyFirefox supports the JavaScript string constructor propertySafari supports the JavaScript string constructor propertyOpera supports the JavaScript string constructor property