03. Constructor Property

All types in JavaScript (except the null and undefined values) have a constructor property, which is a part of the inheritance. The constructor property in a prototype is automatically setup to reference the constructor function. Because properties are inherited from the prototype, the constructor is available on the instance object too.

For example:

const num = 150;
num.constructor === Number; // => true

const str = "abc";
str.constructor === String; // => true

const obj = {};
str.constructor === Object; // => true

const reg = /\d/g;
reg.constructor === RegExp; // => true

It serves as a public identity of the class, which means it can be used for:

  • Identify to what class belongs an object (an alternative to instanceof)

  • Reference from an object or a prototype the constructor function

  • Get the class name

Constructors for primitive types

In JavaScript the primitive types has a constructor property, which refers to the corresponding type function:

  • Number() for numbers: (1).constructor === Number

  • Boolean() for boolean: (true).constructor === Boolean

  • String() for strings: ('hello').constructor === String

  • Symbol() for symbols: Symbol().constructor === Symbol

constructor is a regular non-enumerable property in the prototype object. It does not update automatically when a new object is created based on it. When creating a subclass, the correct constructor should be setup manually.

Last updated