JavaScript: What's Constructor?

By Xah Lee. Date: . Last updated: .

What's a Constructor?

There's no mathematicically precise definition of “Constructor”.

In practice, when a function is designed to be called with the keyword new, for example new f(), we call the function constructor.

(There are some exceptions. For example, the constructor Symbol cannot be called with new [see Symbol Tutorial])

JavaScript spec defines constructor to be a function that creates and initializes objects. Quote:

function object that creates and initializes objects

NOTE The value of a constructor's prototype property is a prototype object that is used to implement inheritance and shared properties.

ECMAScript 2015 §Overview#sec-constructor

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

Builtin Constructors

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

const x = new Date();

Here's example of standard builtin constructors.

Common Builtin Construtors
ConstrutorLiteral ExpressionConstructor Syntax
Object{}new Object()
Array[]new Array()
Functionfunction () {}new Function()
RegExp//new RegExp()
Datenonenew Date()

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 named “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

JS in Depth
XAH  BUY NOW

JS in Depth

JS Obj Ref

DOM


JS in Depth

Basic Syntax

Value Types

Variable

String

Function

Property

Object and Inheritance

Array

Constructor/Class

Iterable 🌟

Misc