The keyword "new" in JavaScript

Swarnali Roy - Sep 19 '21 - - Dev Community

Hello Readers!
Let me introduce you all with something new today!

The topic today is the JavaScript Keyword "new"! In JavaScript, the keyword new is used to create an instance of an object that has a constructor function.

Before diving into the details, we need to understand one thing, that is, in JavaScript almost everything is an Object and the concept of Object is very important to understand the keyword "New". When we define any Boolean, Number or String with the keyword New, it can be treated like an object.

Let me show an example first!

Construction Function

πŸ‘‰ This is a "constructor function" , Animal since it is responsible for constructing a new object, animal.
πŸ‘‰ We had to add properties to the animal object with the dot notation and return it from the constructor function.
πŸ‘‰ Let's assume that we need to create more than one Animal object in our application. So, we instantiated the constructor function twice.
πŸ‘‰ We can see the output where two new animal objects are created with name and legs properties.

Here is the interesting thing about the keyword new. When we use the keyword, a property called this is created which refers to the whole object and is returned automatically. So, we don't need to specify any additional object inside our constructor function. Basically, those two lines are done for us implicitly (under the hood).

Let's take a look what happens under the hood , assuming the Animal constructor is called with the new keyword. It can be re-written as following and it is equivalent to the previous example:

With Comments

Here, a new object is automatically created and returned. (the commented out lines)

We can compactly write the code without the under the hood comments:

Without Comments

This concept is known as "Pseudoclassical Instantiation".

Similarly, we can define an Object property which is itself another Object!

For example, let's define an object called "Human" And then instantiate two new Human objects as follows:

Human

Now, suppose we want to create an object type for cars and name it "Car". It should have properties named owner, model and yearOfPurchase. Instead of passing a literal string or integer value while creating the new objects, the following statements pass the objects man and woman as the parameters for the owners.

Car

To find out the name of the owner of car2, we can access the property as follows:

console.log(car2.owner.name); //Swarnali
Enter fullscreen mode Exit fullscreen mode
Hope this post help you while creating a lot of similar objects in your application. Discussion and queries are always welcomed! ☺️☺️
. . . . . . . . . . . . . . . . . . . . . .