What is a constructor in JavaScript?

A constructor is a function that creates an instance of a class which is typically called an “object”. In JavaScript, a constructor gets called when you declare an object using the new keyword.

The purpose of a constructor is to create an object and set values if there are any object properties present. It’s a neat way to create an object because you do not need to explicitly state what to return as the constructor function, by default, returns the object that gets created within it.

Example

Let’s say there is an object, User, which has two properties: firstname and lastname.

To initialize two instances with different names, you will use the same constructor function, as shown in the figure below:

svg viewer

What happens when a constructor gets called?

In JavaScript, here’s what happens when a constructor is invoked:

  • A new empty object is created

  • this keyword starts referring to that newly created object and hence it becomes the current instance object

  • The newly created object is then returned as the constructor’s returned value

Given below is the code to initialize two user instances just as shown in the above illustration:

function User(first, last) {
this.firstName = first
this.lastName = last
}
var user1 = new User("Jon", "Snow")
console.log(user1)
var user2 = new User("Ned", "Stark")
console.log(user2)

Default constructors

In JavaScript, if you don’t specify any constructor, a default constructor is automatically created which has no parameters:

constructor(){
}

Note: Constructors have the same name as that of the object which is being created. As a convention, the first alphabet is kept capital in the constructor function.

Copyright ©2024 Educative, Inc. All rights reserved