The concept of the new operator is from class-based object-oriented languages such as C++ and Java. It is used to create an instance or object of a class and in general, it mainly does two things:

Instantiating — allocating spaces in memory for the object being created, and

Initialization — executing the constructor method and initializing the object (e.g. its member variables and member functions).

For JavaScript, it is not a class-based language like Java, it is prototype-based, so its new operator does its very specific things and is very different from the new operator in Java.

According to MDN:

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

For example, we create a constructor function below and use the new operator to create an instance of this constructor function:

function Employee(name) {
  this.name = name;
}

const employee = new Employee('Mike');

Employee() is just a normal function in JS, and when we use the new operator in front of it, it becomes a “constructor function”. Now an object of the constructor is created, and its reference is assigned to the constant variable employee.

As per MDN, the new operator does the following four things:

Creates a blank, plain JavaScript object;

Links (sets the constructor of) this object to another object;

Passes the newly created object from Step 1 as the _this_ context;

Returns _this_ if the function doesn’t return an object.

Also,

Creating a user-defined object requires two steps:

Define the object type by writing a function.

Create an instance of the object with _new_.

With the official definition in hand, let’s implement the new operator ourselves.

First, create a function named **_New. _**It takes a couple of parameters and the first parameter is the constructor function being passed in. We use the rest syntax to collect the rest parameters into an array named args.

function New(constructor, ...args) {

}

#front-end-development #interview-questions #javascript #web-development #javascript-tips

Implement JavaScript’s new operator yourself — A killer Frontend interview question
1.15 GEEK