Skip to main content

Command Palette

Search for a command to run...

The new Keyword in JavaScript

Understand how JavaScript creates objects behind the scenes.

Updated
3 min read
The new Keyword in JavaScript

Why Do We Need new ?

In JavaScript, we often want to create multiple objects with similar structure.

Without Constructor

const user1 = { name: "Tony", age: 24 };
const user2 = { name: "Steve", age: 25 };

This gets repetitive and hard to scale.

Enter Constructor Function

A constructor function helps us create multiple objects easily.

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

Using The new Keyword

const user1 = new User("Tony", 24);
const user2 = new User("Steve", 25);

What Does new Actually Do?

This is where things get interesting:

When we use new , JavaScript performs 4 steps automatically.

Step-by-Step Object Creation

Step-1: Create an empty object

{}

Step 2: Bind this to the object

this -> {}

Step 3: Link Prototype

object.__proto__ → User.prototype

Step 4: Return The Object

return {}

Visual Flow

new User("Tony", 24)

   ↓
[Empty Object Created]
   ↓
[this binds to object]
   ↓
[Prototype linked]
   ↓
[Object returned]

Final Result:

{
  name: "Tony",
  age: 24
}

This is a key concept:

User.prototype.greet = function () {
  return `Hello ${this.name}`;
};

const user1 = new User("Viraj", 24);

console.log(user1.greet());

What's happening?

user1 → doesn't have greet()
   ↓
looks into prototype
   ↓
User.prototype → greet() found ✅

Constructor vs Object Relationship

User (Constructor)
      ↓
User.prototype
      ↓
user1 instance

Think Like This:

  • Constructor --> Blueprint

  • Object --> House

Instances Created From Constructor

Each time we use new , we create a new instance.

const user1 = new User("Tony", 24);
const user2 = new User("Steve", 25);

Key Point

user1 !== user2
(but share same prototype)

Common Mistake:

Forgetting new :

const user = User("Tony", 24);
  • This will not create an object correctly

  • this may point to the global object

Advance Insights

We can mimic new manually:

function myNew(constructor, ...args) {
  const obj = {};
  obj.__proto__ = constructor.prototype;
  constructor.apply(obj, args);
  return obj;
}

Summary

Concept            | Meaning
------------------|----------------------------
new keyword       | Creates object from function
Constructor       | Blueprint for objects
Prototype         | Shared methods
Instance          | Object created using new

Why This Matters?

  • Foundation of Object Oriented JS

  • Helps understands prototype

  • Essential for interview

  • Builds mental model for JS