What is New in JavaScript

What is a New Keyword?

In JavaScript, the 'new' keyword is employed to generate a new object instance by utilizing the constructor method. This signifies that upon creating a fresh instance, the constructor method in JavaScript is invoked each time an instance is created.

Put plainly, the new keyword is utilized to generate an object instance that contains a constructor method. By employing the new keyword, users can produce instances of both user-defined and pre-existing object types. This technique allows for the creation of instances from classes, prototypes, or constructor methods.

In JavaScript , when we create a function with new keyword the function is used as constructor. The new keyword will do the following:

  • First, it will create an empty JavaScript object.
  • After that, it will set its prototype for inheritance.
  • The 'this' variable is made to point to the newly created object. It helps us to bind the property that is declared with this keyword to the new object.
  • It also executes the constructor method using new created object whenever it is used.
  • It returns a newly created object unless the constructor function returns a non-null object reference.

Syntax

Example

new Constructor(arguments);

Parameter

Function Constructor: In JavaScript, it refers to the name of the function used to create objects or the name of a class.

Concept: Within JavaScript, it is possible to provide several arguments for the initialization of object properties simultaneously.

Using the 'new' keyword with Function Constructor

When working with JavaScript, in order to utilize a function as a constructor, it is necessary to invoke the function with the new keyword preceding the function name.

In JavaScript, it is possible to create numerous objects by employing a function constructor. This method serves as the prototype for the object.

Syntax:

Below are the formats for the syntax of both the "new" keyword and the constructor function:

Example

new FuncName (argument);

Example

Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
<script>
      function Watch(brand, price, type) {
      this.brand = brand;
      this.price = price;
      this.type = type;
   }
   const rolex = new Watch('Rolex', 40000, 'analog');
   const sonata = new Watch('sonata', 3000, 'digital');
   document.getElementById('output').innerHTML += 
   "The rolex object is: " + JSON.stringify(rolex) + "<br>" +
   "The sonata object is: " + JSON.stringify(sonata);
  </script>
</body>
</html>

Explanation

In the previous instance, we established the constructor function called Watch. This constructor function sets up the properties for brand, price, and type. Subsequently, we instantiated two new objects using the Watch constructor and displayed them in the output.

Output:

Output

The rolex object is: {"brand":"Rolex","price":40000,"type":"analog"}
The sonata object is: {"brand":"sonata","price":3000,"type":"digital"}

Using 'new' keyword with Class

Within JavaScript, it is possible to establish an instance of a class by employing the new keyword. By utilizing the new keyword alongside the class, a blueprint for the object is supplied.

Before the introduction of ES6, object templates were created using constructor functions, whereas after ES6, classes are utilized for this purpose.

Example

Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const output = document.getElementById('demo')
    class WindowClass {
       constructor(color, size, type) {
          this.color = color;
          this.size = size;
          this.type = type;
       }
       getDetails = function () {
          output.innerHTML =  
        "Color: " + this.color + "<br>" +
          "Size: " + this.size + "<br>" +
          "Type: " + this.type;
       }
    }
    // Creating the instance of WindowClass class
    const window1 = new WindowClass('red', 'large', 'wooden'); 
    // Calling function object
    window1.getDetails(); 
 </script>
</body>
</html>

Explanation

In the example provided, we have established the 'WindowClass class'. Within this 'WindowClass', we have included a constructor for property initialization. Additionally, the class contains the getDetails method.

Subsequently, we instantiated an object of the WindowClass by utilizing the 'new' keyword along with the class name.

Output:

Output

Color: Red
Size: large
Type: wooden

Using 'new' keyword with a built-in object

The new keyword can be utilized to instantiate a built-in object that has a constructor function.

Syntax

Example

const num = new Number (20);

In the syntax mentioned earlier, a numerical value is provided as an argument to the Number constructor.

Example

Example

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body>
  <script>
    const num = new Number(10);
    const str = new String("Hello");
    document.getElementById("output").innerHTML = 
  "num = " + num + ", typeof num " + typeof num + "<br>" +
    "str = " + str + ", typeof str " + typeof str;
 </script>
</body>
</html>

Output:

Output

num = 10, typeof num object
str = Hello, typeof str object

The purpose of the new keyword in JavaScript

Creating a new object

In JavaScript, the new keyword is employed to generate a fresh instance of an object. Invoking a constructor function using new results in the creation of the object.

Example

Example

function Bike(model) {
this.model = model;
}
const myBike = new Bike ('Ducati');
console.log(myBike.model); //Ducati

Setting the prototype

In JavaScript, the internal [[Prototype]] property of a newly created object is assigned to the prototype property of the constructor function. This mechanism enables the new object to inherit the properties and methods defined in the constructor's prototype.

Example

function Animal(type) {
this.type = type;
}
Animal.prototype.speak = function() {
console.log(`${this.type} makes a sound`);
}

Binding this to the new object

When working with JavaScript, this within the constructor function denotes the fresh object in the process of creation. This concept enables us to incorporate properties and functions into the newly formed object.

Example

function Book(title) {
    this.title = title;
    }
    const myBook = new Book ('The Lord of the Rings');
    console.log(myBook.title); //The Lord of the Rings

Returning the new object

In JavaScript, when the 'new' keyword is used with a constructor function, it automatically returns the object that was created. However, if the constructor function explicitly returns an object, that specific object will be the one returned.

Example

function Gadget(name){
    this.name = name;
    return {type: 'Electronic'};
    }
    const myGadget = new Gadget('Laptop');
    console.log(myGadget.type); //Electronic
    console.log(myGadget.name); //Laptop

Conclusion

Within JavaScript, the utilization of the new keyword is pivotal when it comes to constructing objects and is essential for enabling the language's object-oriented features. When the new keyword is used to call a constructor function or a class, a fresh object instance is produced. This new object possesses its individual properties and methods, following the structure outlined by the constructor. This operation encompasses establishing the prototype chain, associating the this context with the fresh object, and managing the object creation return.

Input Required

This code uses input(). Please provide values below: