Skip to main content

Command Palette

Search for a command to run...

The `new` Keyword in JavaScript

Published
3 min read
The `new` Keyword in JavaScript

In JavaScript, you might have seen new in code like:

const user = new User()

We use it, but many times we don’t really know what it’s doing internally.

It feels like it just creates an object.

But actually, a lot of things are happening behind the scenes.

In this blog I will share how I understand the new keyword and what really happens when we use it.


What the new keyword does

When you use new, JavaScript creates a new object for you.

But not just that.

It also connects things, sets values and returns that object.

So new is doing multiple steps, not just one.


Constructor functions

To use new, we usually have something called a constructor function.

Example:

function User(name, age) {
  this.name = name
  this.age = age
}

Now we use:

const user1 = new User("Dhiraj", 20)

Here:

User is a constructor --> user1 is an instance


How it actually feels

constructor = blueprint

instance = real object


Object creation step by step

When we do:

const user1 = new User("Dhiraj", 20)

JavaScript does this internally:

Step 1: create empty object

{}

Step 2: set this to that object

Inside function:

this → {}

Step 3: add properties

this.name = "Dhiraj"
this.age = 20

Now object becomes:

{ name: "Dhiraj", age: 20 }

user1.__proto__ = User.prototype

so it can access shared methods


Step 5: return object

Final result:

user1

Constructor → instance flow


How prototype is linked

function User(name) {
  this.name = name
}

User.prototype.sayHi = function () {
  console.log("Hi " + this.name)
}

const user1 = new User("Dhiraj")
user1.sayHi()

Why this works?

because user1 is linked to User.prototype

So it can access sayHi


Prototype visual idea


Instances created from constructors

const u1 = new User("A")
const u2 = new User("B")

both are different objects

But:

share same prototype

So methods are not duplicated.


Why new is useful

Without new, you would have to manually:

  • create object

  • assign values

  • link prototype

new does all that automatically.


What happens if we don’t use new

const user = User("Dhiraj", 20)

Now:

this = global object

So it can break things.

That’s why new is important here.


Simple way to remember

new does:

create object --> bind this --> link prototype --> return object