Constructor in JavaScript
Posted by Superadmin on May 02 2023 15:14:27

Constructor in JavaScript

By Priya PedamkarPriya Pedamkar
  

Constructor in JavaScript

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

constructor in java

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 –

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:

constructor method

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:

object consuctor

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:

object consuctor.2png

Code:

var now = new Date();
console.log(now);

Output:

object consuctor.3png.png

Code:

var err = new Error("A user-defined error has occurred.");
console.log(err);

Output:

object consuctor.4png

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:

custom 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.

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:

imp 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:

imp output2.png

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.