The new Keyword in JavaScript

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.
What Does the new Keyword Actually Do?
When a function is called with the new keyword, the function will be used as a constructor.
new operator will do the following things:
It creates a new object.
It sets this new object's internal, inaccessible,
[[prototype]](i.e.__proto__) property to be the constructor function's external, accessible,prototypeobject (every function object automatically has aprototypeproperty).It makes the
thisvariable point to the newly created object.It executes the constructor function, using the newly created object whenever
thisis mentioned.It returns the newly created object, unless the constructor function returns a non-
nullobject reference. In this case, that object reference is returned instead.
Note - Classes can only be instantiated with the
newoperator — attempting to call a class withoutnewwill throw aTypeError.
The new with constructor functions
Constructor functions in JavaScript are regular functions designed to create and initialize multiple objects with shared properties and methods.
Creating an object with a user-defined constructor function requires two steps:
Define the object type by writing a function that specifies its name and properties. For example, a constructor function to create an object
Personmight look like this:function Person(name,email){ this.name = name; this.email.email; }Create an instance of the object with
new.const mukul = new Person("Mukul","mukul123@gmail.com");
The new with classes
class Person {
constructor(name) {
this.name = name;
}
greet() {
console.log(`Hello, my name is ${this.name}`);
}
}
const p = new Person("Mukul");
p.greet(); // Hello, my name is Mukul
The Object Creation Process and the new Links Prototypes
In the object creation with the new keyword , the js perform the five steps.
Creates a brand new empty object
{}— let’s call itnewObj.Links the new object’s prototype
Sets
newObj.__proto__(or more accurately,[[Prototype]]) toPerson.prototype.Binds
thisto the new objectInside the constructor function,
thisnow refers tonewObj.Executes the constructor body
The code inside
Person()runs, attachingnameandemailvalue tonewObj.Returns the new object (automatically)
No need to mention
returnexplicitly, JavaScript returnsnewObjfor you automatically and implicitly.
And in the new prototype linking process, every instance created with new Person() has instance.__proto__ = Person.prototype.


