JavaScript: What is Constructor

By Xah Lee. Date: . Last updated: .

What is a Constructor

Constructor is meant to create a object that is specific to certain type of data. (for example, create a date object, array object, etc.)

In practice, when a function is designed to be called with the Operator “new” , e.g. new f(args), the function f is called constructor. (There are some exceptions. For example, the constructor Symbol cannot be called with new [see Symbol Tutorial])

Constructor is one of the way to create object. [see Create Object]

Builtin Constructors

The most common use of Operator “new” is to create a builtin object instance, such as Date object.

const x = new Date();

Here is example of standard builtin constructors.

Common Builtin Construtors
ConstrutorLiteral ExpressionConstructor Syntax
Object{properties}new Object(args)
Array[items]new Array(args)
RegExp/pattern/flagnew RegExp(args)
Datenonenew Date(args)

There are many more constructors. Builtin objects almost always have a constructor. [see JavaScript Object Reference]

Primitive Value Wrapper Constructors

The following are constructors for Primitive Value 's wrapper objects. (when you call a method on a primitive value, such as "a,b".split(","), the string is temporarily converted to a string object. That's why it has methods.)

User Defined Constructor

Two common ways to define your own constructor:

Parenthesis Optional for Constructor Call with No Args

When a function is used as a constructor and without argument, the parenthesis are optional. For example, new F() and new F are equivalent.

Do Not Confuse with Property Name “constructor”

Do not confuse constructor with property key "constructor".

[see Property Key "constructor"]

💡 TIP: Use Literal Expression When Possible

For builtin objects, you should use the literal expression to create object whenever possible. Because:

💡 TIP: Constructor Name Start with Capital Letter

By convention, functions designed to be used as constructor starts with a capital letter.

JavaScript Constructor/Class

BUY ΣJS JavaScript in Depth