In JavaScript, it is important for you to understand how you can create reusable objects in order to write efficient and organized code. One of the best ways you can do this is by using JavaScript constructors. JavaScript constructors are special functions that are used to build objects and initialize the same objects.
In this blog, you are going to learn about what a JavaScript constructor is, why it is useful, how you can create a constructor, and how you can use it properly in your projects. So let’s get started!
Table of Contents:
What is a Constructor in JavaScript?
A JavaScript constructor is a special type of function that helps you to set up and create objects. You can take it as a blueprint that instructs JavaScript on how to build a new object. Usually, it is used along with the new keyword.
When you create a new object using a JavaScript constructor, it runs automatically and then sets up the starting values, like the name, age, or anything else that is required by the object. It also adds any methods (functions) that are necessary for the object to have. This makes it easier for you to work with the object later.
A sample code for a constructor in JavaScript is given below for your reference:
Code:
Output:
Explanation:
The above code is used to create a constructor function named Person. It is used to create objects with a name, age, and a method called greet. When you create a new object using new Person(…), it sets the name and age for that object. The greet method then prints a message that introduces that person. In the above example, two objects, person 1 and person 2, are created using different names and ages. Their properties are then accessed using the dot notation, and then the greet() methods are called to display the personalized greetings in the console.
Boost Your Resume With Real Skills
Join Our Web Dev Course
How Do Constructors Work in JavaScript?
A JavaScript constructor is a special type of function that is used to create and initialize objects. It tells JavaScript how to make a new object. When you use the new keyword with a constructor function, JavaScript automatically does all the things for you.
1. It first creates a new empty object.
2. Inside the constructor, the word this refers to the new object.
3. The code present inside the constructor is used to set up the properties and methods of the objects.
4. After everything is set, it automatically returns the new object.
A sample code is given below for your understanding.
Code:
Output:
Explanation:
The above code used a JavaScript Constructor called Animal in order to create objects that represent animals. When a new animal is created using new Animal(…), it sets up two properties: the first one is type (like “Dog” or “Cat”) and the second one is sound (like “Woof” or “Meow”). After that, it adds a method called makeSound() that prints a message which shows what sound is made by the animal.
Types of Constructors in JavaScript
While you are working with objects in JavaScript, you need a clean and structured way to create multiple similar objects. This is where you can use the JavaScript constructor. There are two types of constructors in JavaScript. They are as follows:
1. Constructor Function.
2. Class Constructor.
Each of the two types of Constructors is explained below:
1. Constructor Function
A constructor function is a regular function that works like a blueprint for creating objects. You can define it with a capitalized name and using the new keyword for creating new instances. An example of a constructor function is given below for your reference:
Code:
Output:
Explanation:
The above code uses a JavaScript constructor function called Car, which is used to create car objects. When a new car is made using new Car(), it sets the two properties: brand and year. It also adds a new method called showDetails(), which then prints the brand and the year of manufacture of the car.
2. Class Constructor (ES6)
In JavaScript, the keyword class was introduced in ES6 in order to make object-oriented programming much easier and cleaner. A class constructor is always defined inside a class using a special method named constructor. An example code for class constructor is given below for your reference:
Code:
Output:
Explanation:
The above code is used to define JavaScript constructor using the class syntax. The class is named Student, and it consists of a special method called constructor(). This method helps to set up the name and grade of the student where a new object is created. There is also a method which is called displayInfo(), which is responsible for printing the name and grade of the student.
How to use Constructors in JavaScript
Here, we will explore some examples of JavaScript Constructors to understand how they are used.
1. Using the “this” Keyword in Constructors
In a JavaScript Constructor, the this keyword is used to point to the new object that is created. You can use the this keyword to set the values for the properties of that object, like giving it a name, age, anything else.
Code:
Output:
Explanation:
The above code is used to define a JavaScript constructor named Cars. It creates car objects along with their details like manufacturer, model, and year. The this keyword is used to assign values that are passed (like Tesla, CyberTruck, and 2024) to the new car. After myCar is created, all the information is stored in it, and with the help of console.log, all the properties can be displayed separately.
2. Creating Multiple Objects with Constructors
JavaScript constructor helps you to create many objects by using the same blueprint. You don’t have to write the same code again and again. Every object that is made with the constructor will have its own values, like name, age, or anything else. So, instead of copying the code, you just have to call the constructor to build as many objects you want, each consisting of its own data.
Code:
Output:
Explanation:
The above code is used to define a JavaScript constructor called Circle. It helps you to create circle objects with a given radius. Inside the constructor, the this keyword is used to set the radius and define a method getArea() to calculate the area of the circles. After you have created circle1 and circle2, each one will have its own radius and can also calculate its own area.
3. Constructor with Parameters
In JavaScript constructor functions, you can also pass values (parameters) while creating a new object. This helps to give each object its own details. For example, if you use a constructor to make rectangles, you have to pass different lengths and widths for each rectangle, so that every rectangle has its own size.
Code:
Output:
Explanation:
In the above code example, the JavaScript constructor named Rectangle is used to create rectangle objects having their own height and width. When rectangle1 and rectangle2 are created, you have to pass different values, so that each object stores its own size. Then the getArea() function is used to calculate the area of each rectangle.
4. Constructor vs Object Literal
In JavaScript, objects can be created in many ways. If you only need one object with some specific properties, it will be easy for you to use an object literal. But if you want to create many similar objects that have the same structure, it is more efficient to use a JavaScript constructor. Constructors in JavaScript help you to reuse the same template for building as many objects as you need, each having their own values.
Code:
Output:
Explanation:
The above code is used to show two ways to create objects in JavaScript. At first, by using a constructor function (Personat) and by using an object literal. person1 and person2 are made using the constructor, which helps you to create similar objects with different values. person3 is made directly using an object literal, which can be useful when you need only an object. At last, the console.log() prints the name and age of the person.
5. Understanding Object Prototypes
In JavaScript, prototypes help you to share properties or methods across multiple objects without repeating your code. When you create objects using a constructor, you can use the prototype to define functions or values so that every object created from that constructor can use it. This helps to keep your code clean and memory-efficient. Now, let us look at an example by using a constructor named Person where we will add a common method to its prototype.
Code:
Output:
6. Built-in Constructors in JavaScript
JavaScript constructors consist of some built-in constructor functions like String(), Number(), Boolean(), Array(), and Object(). These functions help you to create specific types of objects. For example, you can create a string by using the function new String(“hello”). But in most cases, it is better to use simple values like “hello” instead of creating them with constructors. This is because primitive values are much faster and easier to work with. Given below are some examples of built-in constructors:
var stringObject = new String('Hello');
var numberObject = new Number(24);
var booleanObject = new Boolean(true);
var arrayObject = new Array(1, 2, 3);
var dateObject = new Date();
The code for each built-in constructor is given below for your reference:
Code:
Output:
Get 100% Hike!
Master Most in Demand Skills Now!
Best Practices for Using JavaScript Constructors
Given below are the best practices for using JavaScript constructors:
1. Always name your JavaScript constructor with a capital letter (like Person, Car) so that it becomes easy to identify that it is a constructor and not a regular function.
2. When you are using a JavaScript Constructor, you should always use the new keyword to create a new object.
3. Instead of defining functions inside each object, you should add shared methods to the prototype. This helps you to save memory and keep your code clean.
4. In order to get better performance, try not to use constructors like new String(), new Number(), or new Boolean(). Instead, you can use primitive values (‘text’, 42, true).
5. You need to insert default values into your JavaScript constructor, so that you do not have any issues when no arguments are passed.
Conclusion
A JavaScript Constructor is a convenient tool for creating multiple similar objects that have some common properties and methods. You can make less complex and more effective code by following a few best practices, like using prototypes, naming constructors with capital letters, and avoiding unnecessary dependencies. After knowing how a JavaScript Constructor works, you will find it quite easy to organize your code and create larger applications. If you are an aspiring web developer, then explore our blog and enroll in our web development course.
Constructors in JavaScript – FAQs
Q1. Can I use an arrow function as a JavaScript constructor?
No, arrow functions are not capable of serving as constructors since they don’t have their own this context.
Q2. Is it okay to return a value from a JavaScript constructor?
You can return an object in a manual way, but it is not a common practice unless something specific is returned.
Q3. What happens if I forget to use new with a JavaScript constructor?
In the absence of new, the constructor does not create a new object. Instead, it might update values of the global object.
Q4. Can a JavaScript Constructor call another constructor?
Indeed, you can call one constructor inside another constructor using the .call() or .apply() methods.
Q5. Are JavaScript Constructors only used for objects?
Mostly yes, they are used to create object instances with specific structures or behavior.