Skip to main content

Command Palette

Search for a command to run...

The new Keyword in JavaScript

Updated
•1 min read•View as Markdown

What the new keyword does?

When you use new with a function, JavaScript performs a series of internal steps:

  1. Creates a new empty object

  2. Links that object to a prototype

  3. Binds this to the new object

  4. Executes the constructor function

  5. Returns the object (unless explicitly overridden)

lets try to create object using new keyword

Object Creation Process

function User(name, email) {
  this.name = name;
  this.email = email;
}

const user1 = new User("Krish", "krish@example.com");

Internal process

const obj = {};
obj.__proto__ = User.prototype;
User.call(obj, "Krish", "krish@example.com");
return obj;

life is simpler than before.

How new Links Prototypes?

Every function in JavaScript has a prototype property.

When using new:

  • The created object’s internal [[Prototype]] is set to the constructor’s prototype

Which we just saw from above code.

Instances Created from Constructors

Objects created using new are called instances.

const user2 = new User("Amit", "amit@example.com");

console.log(user2 instanceof User); // true

Each instance:

  • Has its own properties

  • Shares methods via the prototype