new operator in javascript

New Operator in JavaScript

The "new" operator in JavaScript is used to create a new instance of an object. It is used with constructor functions to create a new object of that function.

How to use the "new" operator:

To use the "new" operator, you first need to create a constructor function. A constructor function is a function that initializes an object. You can create a constructor function like this:


function Person(name, age) {
  this.name = name;
  this.age = age;
}

The above code creates a constructor function called "Person" that takes two parameters, "name" and "age". Inside the function, we use the "this" keyword to set the name and age properties of the newly created object.

To create a new instance of the Person object, we use the "new" operator like this:


var person = new Person("John", 30);

The above code creates a new instance of the Person object with the name "John" and age "30". The "new" operator creates a new object and sets its prototype to the Person.prototype. It then calls the Person function with the newly created object as its "this" keyword.

Using "new" operator with built-in constructors:

You can also use the "new" operator with built-in constructors such as String, Number, and Array. For example:


var str = new String("Hello");
var num = new Number(10);
var arr = new Array(1, 2, 3);

The above code creates a new instance of a string, number, and array respectively using the "new" operator.

Using "new" operator with ES6 classes:

In ES6, you can use the "class" keyword to define a class and create objects using the "new" operator. For example:


class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }
}

var person = new Person("John", 30);

The above code creates a Person class with a constructor function that takes two parameters, "name" and "age". It then creates a new instance of the Person object using the "new" operator with the name "John" and age "30".

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe