Code360 powered by Coding Ninjas X Naukri.com. Code360 powered by Coding Ninjas X Naukri.com
Table of contents
1.
Introduction
1.1.
Constructors
1.2.
This Keyword
2.
New Keyword
2.1.
Creating New Objects From Constructors
2.2.
Target Attribute Of New
2.3.
Return Object Explicitly From Constructor
2.4.
Methods inside Constructor
3.
Frequently Asked Questions
3.1.
What are constructors?
3.2.
How are constructors in JavaScript different than constructors in another programming language?
3.3.
Why do we use “new” in JavaScript?
3.4.
What is “this”, and how does it work in JavaScript?
3.5.
Can a constructor return something?
4.
Conclusion
Last Updated: Mar 27, 2024
Easy

“New” Constructor operator in JavaScript

Create a resume that lands you SDE interviews at MAANG
Speaker
Anubhav Sinha
SDE-2 @
12 Jun, 2024 @ 01:30 PM

Introduction

Hey Ninjas!!, Today we'll be talking about new constructor operator in JavaScript. But before we start, let's talk about what a constructor is.

Introduction Image

Also See, Javascript hasOwnProperty

Constructors

A constructor is a particular type of function used to initialize attributes on creating an object of the class. In simpler words, when you create an object of a class, you are supposed to initialize all the attributes of the objects, which is done using the constructor. 

There are different types of constructors: Parameterized, Default, etc. If you want to know more about them, click here

Different programming languages have other methods of creating constructors. Here we will focus on JavaScript and how to create a new class object.

constructor workflow

Here is a workflow of how JavaScript works when creating a new object.

This Keyword

You may have come across this object when working with any object-oriented programming language. For those of you who are not familiar with this object, here’s a brief intro about this.

‘this’ is an object which is defined inside a class or a function and is locally scoped inside the body. It is returned by default, from a constructor, or from a function when called as a constructor. 

Now that you are familiar with these topics. Let’s get started with the ‘new’ keyword in JavaScript, and how it is used to create a new object of a class or function, and how it relates to a constructor.

New Keyword

One can always create a new JavaScript object via {...} spread operator. Still, there are times when you want to create a new JavaScript object entirely rather than inheriting attributes from the existing objects.

So to create a new object, the new operator comes in handy. Here we will look into all the different functionalities of the new keyword.

Creating New Objects From Constructors

It creates new objects of any class defined in the JavaScript code. For declaring a constructor in JavaScript, we have to follow some guidelines:

  • The function name should start with a Captial Letter
  • Use the keyword new before the constructor call. 
     

Let's look at some examples to get a clear picture.

class Animal {
constructor(breed, petName, diet) {

   	// Creates a object called this
   	// this = {}

   	// Constructor assigns the attributes to the this object
   	this.breed = breed;
   	this.petName = petName;
   	this.diet = diet;

   	// Now the value of this object becomes
   	// this = {breed:breed, petName:petName, diet:diet}
   	// return this
 }
}

let cat = new Animal("Cat", "Tom", "Milk");
console.log(cat);


Output

output 1

Explanation

As you can see, we created a new object with the help of a new operator. This object belongs to the class Animal defined above. The Animal class has three attributes defined(declared with this object), i.e., breedpetName, and diet, which are initialized with the help of the constructor. 

Now let's understand the work behind the operator.

  • When we call the constructor using the new operator, it creates a new empty object inside the class with the name this. As seen above, when we create a new object of Animal class, we create a this object of the class, and the attributes are initialized with values passed. 
     
  • It then adds the attributes/properties to this object. The values are passed as arguments to the function call. Now the value the attributes are breed: “Cat”, petName: “Tom”, diet: “Milk”.
     
  • The JavaScript object is created with the class and returned from the constructor. Here the constructor returns the this object, defined in the Animal class.
     

But here's a doubt that users frequently ask. Why should one follow the above typical code when one can create an object using this simple code?

let animal = {
 	breed: "Cat",
 	petName: "Tom",
 	diet: "Milk",
};


The reason behind using the new operator over creating an object is that, what happens when you are supposed to create 5-6 animal objects with the same attributes?

You will create such individual objects for 5-6 times, which will result in increasing the line of code and won’t look good.

Instead, we create one class to define all the attributes, which helps in creating JavaScript objects in a single line via the new operator.

Target Attribute Of New

Have you ever wondered, what happens when you call a constructor or a function? 

For instance, when you see a function call, how does JavaScript know that the function was called as a constructor and not as a general function call?

Don't worry; we got you covered; here's how JavaScript works.

It attaches a target property/attribute when called with the new operator. So you can access new when you call any function, as a constructor, inside the function body, with new.target. If it is undefined, then the function call was simple, else it was called as a constructor (accompanied by the new operator).

function sayHello(){
 	console.log(new.target)
}
sayHello()


Output

output 2

Now when we call the function with the new keyword, we get the object of type function sayHello.

function sayHello(){
 	console.log(new.target)
}
new sayHello()


Output

output 3

Explanation

As you can see, when the function was called as a constructor, i.e., when called with the new keyword, the new.target attribute is defined with the function declaration. When the function was called without the new keyword, the new.target attribute was not defined; hence undefined was returned. 

Return Object Explicitly From Constructor

As discussed above, from behind the scenes, the constructor returns this object. But what happens when you try to return an object from a constructor explicitly?

Yes, you guessed it correctly, the constructor returns the explicitly defined object. 

So when we reach the end of the constructor, JavaScript searches for the return statement; if we are returning any other object, the constructor returns the explicitly defined object; otherwise, it returns this JavaScript object.

class Animal {
constructor(breed, petName, diet) {
   	// Creates a object called this
   	// this = {}

   	// Assigns the attributes to the object
   	this.breed = breed;
   	this.petName = petName;
   	this.diet = diet;

   	// If no return statement present, then returns this object
   	// Else returns that object
   	return { breed: "Cow", petName: "Mohan" };
  }
}

let cat = new Animal("Cat", "Tom", "Milk");
console.log(cat);


Output

output 4

Explanation

As you can see in the above code, there is an explicitly defined object inside the constructor, so the constructor returns that newly defined object instead of this object.

Methods inside Constructor

Apart from attributes/properties, constructors can also have methods as member objects. 

Methods are member functions for the class defined above. It is a property containing a function definition. 

We can assign any method to this object and then call the method using the object. This helps in increasing the functionality of the class.

class Animal {
constructor(breed, petName, diet) {
   	// Creates a object called this
   	// this = {}

   	// Assigns the attributes to the object
   	this.breed = breed;
   	this.setName = function (name) {
   		this.petName = name;
   	};

   	// Return this object
  }
}

let cat = new Animal("Cat", "Tom", "Milk");
cat.setName("tom");
console.log(cat);


Output

output 5

Explanation

As you can see, we have defined a member function called setName, and have assigned it to this object. So when we call the member function using the object’s class, the function call is executed, and an attribute called petName is initialized with this object, with the value of “tom”. 

So now, when you access the attribute petName, you get “tom” as output.

Get the tech career you deserve, faster!
Connect with our expert counsellors to understand how to hack your way to success
User rating 4.7/5
1:1 doubt support
95% placement record
Akash Pal
Senior Software Engineer
326% Hike After Job Bootcamp
Himanshu Gusain
Programmer Analyst
32 LPA After Job Bootcamp
After Job
Bootcamp

Frequently Asked Questions

What are constructors?

Constructors are member functions of a class, which are called in the same instant as the object is created. They are used to initialize the object with values to their attributes.

How are constructors in JavaScript different than constructors in another programming language?

Constructors in JavaScript follow the same pattern as constructors in any other programming language. Constructors are also used to initialize the object's attributes in different languages.

Why do we use “new” in JavaScript?

The keyword new is used to create an object of a class or a function. Whenever we call any function with the new keyword, the function takes the role of the constructor and returns this object.

What is “this”, and how does it work in JavaScript?

The "this" object refers to the object inside the class or function, where it handles the attributes/properties of the object defined inside the function and implicitly returns the object.

Can a constructor return something?

Yes, a constructor can explicitly return an object or a function. If it does not return anything, it is implied that it will return the implicit this object.

Conclusion

So Ninjas!!, Today you learned about the new keyword in  JavaScript, and how functions work as constructors, and general purpose functions. You also learned about this and new keywords in JavaScript, which are used to create an object of a class or a function. 

If you want to learn more, then check out our articles.

And many more on our platform Coding Ninjas Studio.

Refer to our Guided Path to upskill yourself in DSACompetitive ProgrammingJavaScriptSystem Design, and many more! If you want to test your competency in coding, check out the mock test series and participate in the contests hosted on Coding Ninjas Studio!

But you have just started your learning process and are looking for questions from tech giants like Amazon, Microsoft, Uber, etc. In that case, you must look at the problemsinterview experiences, and interview bundles for placement preparations.

However, consider our paid courses to give your career an edge over others!

Happy Learning!

Previous article
Memory management in JavaScript
Next article
Getters and Setters in Js
Live masterclass