Skip to main content

Command Palette

Search for a command to run...

The "new" Keyword

Updated
2 min read
The "new" Keyword

Introduction

The "new" keyword is a very famous and useful keyword that helps the constructor functions of the of class it is used to create the instances of the classes while creating the object .

We might have thought sometimes that how the object can directly create and access the variables and methods that are defined in the classes. simply we can say that this happens through the "new" keyword.

let's understand how does it works internally.


What happens when we use "new" keyword

  1. Creates a new empty object

  2. Links the prototype

  3. Binds this

  4. Executes the constructor function

  5. Returns the object


1. Creates a new empty object

A fresh object is created in memory.

let obj = {};

The new object’s internal [[Prototype]] (__proto__) is set to the constructor’s .prototype.

obj.__proto__ = ConstructorFunction.prototype;

3. Binds this to the new object

The constructor function is called, and this inside it refers to the new object.

Constructor.call(obj, arg1, arg2);

4. Executes the constructor function

The constructor initializes properties on the object.

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

5. Returns the object

  • If the constructor does not return anything, the newly created object is returned.

  • If it returns a non-primitive (object), that object is returned instead.

  • If it returns a primitive, it is ignored.


Example :

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

Person.prototype.sayHello = function () {
  console.log("Hello " + this.name);
};

const p1 = new Person("Rohit");

p1.sayHello(); // Hello Rohit

Behind the Scenes Equivalent

The new keyword is roughly equivalent to:

function myNew(Constructor, ...args) {
  let obj = {};
  obj.__proto__ = Constructor.prototype;

  let result = Constructor.apply(obj, args);

  return (typeof result === "object" && result !== null) ? result : obj;
}

Conclusion

The new keyword in JavaScript is used to create an instance of a constructor function or class. It internally creates a new object, sets its prototype, binds this to the object, executes the constructor, and returns the initialized object.