Updated March 16, 2023
Introduction to Constructor in JavaScript
The constructor method in JavaScript is a special method used to create and initialize objects within a class. This is what a constructor in every programming language does. What makes JavaScript constructor different from others is the liberty in terms of syntax. To understand it better, simply open the browser developer tools (Ctrl/Cmd + Shift + C) and go to the Console tab in the developer tools window.
It looks like this in Chrome
This is the playground for most of the JavaScript-related concepts. We would be using this playground throughout this article.
Types of Constructor in JavaScript
There are two types of constructors in JavaScript
1. Built-in Constructors
These are the readily available constructors that come bundled with the execution environment. The user simply needs to invoke them and viola, the work’s done. Examples of built-in constructors are Array, Date, and Object.
2. User-defined Constructors
These are the constructors declared and defined by the programmer to be used throughout the application. A programmer can also define properties and methods of their own custom types. They are also known as custom constructors. By convention, all JavaScript constructors are sentence-cased. This is to tell the person using them that this function must be invoked using the new keyword.
How do Constructors work in JavaScript?
Before we look at the syntax of JavaScript constructors, we need to understand a very basic concept of JavaScript –
- The Object class summarizes in the context of this article, every JavaScript object is created by the Object constructor. If the value supplied while creating the object is null or undefined, the Object constructor will create an empty object. Otherwise, it will create an object of the type defined while creating the object.
- Whenever a new object of the class type is declared, the new keyword returns a reference to the newly created object. That object is accessed using this keyword inside the constructor to initialize the properties of the object.
- Although, technically JavaScript doesn’t have any classes but has constructors and prototypes to bring similar functionality. In ECMAScript 2015, the concept of classes was introduced in JavaScript. This was simply a syntactical addition to existing prototype-based inheritance and did not add any new functionality to the language.
Syntax and Examples of Constructor in Javascript
Below are some of the examples given.
1. Constructor Method
Below is the constructor method. This method is used inside the prototype of the class.
Syntax
constructor([arguments]){ ... }
Code
class Employee{
constructor(id, name){
this.id = id;
this.name = name;
}}
var emp1 = new Employee(123, "John");
console.log(emp1.name);
Output:
2. Object Constructor (Built-in Constructors)
The Object constructor is called directly when an object of the class Object is created. This creates an object of class Object if null or undefined parameters are passed as arguments. Otherwise, an object of the type of given parameters is created.
Syntax
new Object([value])
Or
new Array([value])
Or
new Date([value])
Or
new String([value])
Or
new Number([value])
Or
new Boolean([value])
Or
new Function([value])
Or
new Error([value])
Or
new RegExp([value])
and so on…
Code:
var name = new Object("John");
var age = new Object(28);
console.log("Name : "+name+" & Age : "+age);
Output:
3. Array and Date constructors
In a similar fashion, the Array and Date constructors can also be used to create objects of respective types.
Code:
var alphabets = new Array('Apple', 'Ball', 'Cat');
console.log(alphabets);
Output:
Code:
var now = new Date();
console.log(now);
Output:
Code:
var err = new Error("A user-defined error has occurred.");
console.log(err);
Output:
4. Custom Constructors
We can also declare and define our own constructors to be used throughout our application. Let us look at how this can be achieved.
Syntax
function FunctionName([arguments]){ ... }
Code:
function Book(name, author, year) {
this.name = name;
this.author = author;
this.year = year;
}
function displayBook(book){
console.log('\'' + book.name + '\' authored by ' + book.author + ' in the year ' + book.year + '.');
}
var book1 = new Book('Java - The Complete Reference', 'Herbert Schildt', 2006);
var book2 = new Book('Let Us C', 'Yashavant Kanetkar', 2002);
var book3 = new Book('Data Structures', 'Seymour Lipschutz', 2005);
displayBook(book1);
displayBook(book2);
displayBook(book3);
Output:
Importance of new Keyword
Now you may be wondering what if I don’t use the new keyword? Can I omit the new keyword? Well, my friend, no. Using the new keyword is very much essential.
- JavaScript constructors are regular functions. They are accompanied by a new keyword to tell the JavaScript engine that a new object must be constructed with the given properties. Without the new keyword, you would be simply creating more and more global objects.
- The new keyword returns a reference to the newly created object. We then store this reference in a variable. Without the new keyword, the object is created, but no reference to the object is returned. The object assumes a global scope. The only reference to this object is through the window object.
- Confused? Let us understand better with examples. Consider the above example again. We removed the new keyword from the object declarations. The result was an exception to undefined variables. This is because, without the new keyword the newly created objects’ reference wasn’t returned and thus wasn’t stored in our variables book1, book2, and book3. When we tried to access these variables in the display book method, the exception is thrown.
Code:
function Book(name, author, year) {
this.name = name;
this.author = author;
this.year = year;
}
function displayBook(book){
console.log('\'' + book.name + '\' authored by ' + book.author + ' in the year ' + book.year + '.');
}
var book1 = Book('Java - The Complete Reference', 'Herbert Schildt', 2006);
var book2 = Book('Let Us C', 'Yashavant Kanetkar', 2002);
var book3 = Book('Data Structures', 'Seymour Lipschutz', 2005);
displayBook(book1);
displayBook(book2);
displayBook(book3);
Output:
In the same example, if we modify the display book method to access the objects through the window scope, we get an un-expected output.
Code:
function Book(name, author, year) {
this.name = name;
this.author = author;
this.year = year;
}
function displayBook(book){
console.log('\'' + window.name + '\' authored by ' + window.author +' in the year ' + window.year + '.');
}
var book1 = Book('Java - The Complete Reference', 'Herbert Schildt', 2006);
var book2 = Book('Let Us C', 'Yashavant Kanetkar', 2002);
var book3 = Book('Data Structures', 'Seymour Lipschutz', 2005);
displayBook(book1);
displayBook(book2);
displayBook(book3);
Output:
Now, as an exercise, do a little brainstorming to figure out why we get this output!
Scope-Safe Constructors
The built-in constructors in JavaScript are scope-safe constructors. They do not create globally scoped variables when called without a new keyword. Thus, these objects can be safely created with or without a new keyword.
Code
function SampleFn(argument) {
// if "this" is not an instance of the constructor
// it means it was called without new
if (!(this instanceof SampleFn)) {
// call the constructor again with new
return new SampleFn(argument);
}
// The code to construct properties and methods
}
Yes, you too can create user-defined scope-safe constructors. Go on, create a scope-safe constructor for our books in the above example.
Conclusion
This article gave an in-depth demonstration of JavaScript Constructors. This also helps in understanding the working of JavaScript. The key thing to remember here is that although technically there are no classes in JavaScript, the methods and prototypes provide similar functionality at the developer’s disposal. And yes, the new keyword is important.
Recommended Articles
This has been a guide to Constructor in JavaScript. Here we discuss its types and important methods with How to create a scope-safe constructor You can also go through our given articles to learn more-