Skip to main content

Command Palette

Search for a command to run...

The new Keyword in JavaScript

What Actually Happens Behind the Scenes

Updated
•3 min read•View as Markdown

When i first saw the new keyword in JavaScript, it felt a bit magical. You write new something() , and suddenly you have an object. But what actually happens behind the scenes?

Let's break it down in a simple way.


What Actually Happens Behind the Scenes

The new keyword is used to create an object from a constructor function. It doesn’t just call a function — it performs a series of steps automatically to set up that object.


Constructor Functions (The Starting Point)

Before understanding new, we need to understand constructor functions.

A constructor function is just a regular function, but by convention:

  • Its name starts with a capital letter

  • It's name user to create multiple similar objects

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

Now if you call it normally,

User("Dhurandar", 25);

It won’t behave as expected. This is where new comes in.


Object Creation — Step by Step

When you do this:

const user1 = new User("Dhurandar", 25);

JavaScript internally does 4 important things:

  1. Creates a New Empty Object

    const obj = {};
    
  2. Links the Object to the Constructor’s Prototype

    obj.__proto__ = User.prototype;
    
  3. Binds this to the New Object

    User.call(obj, "Dhurandar", 25);
    

so inside the function,

this.name = "Dhurandar";
this.age = 25;

Returns the Object

return obj;

so finally,

const user1 = {
  name: "Dhurandar",
  age: 25
};

How new Connects to Prototypes

Let’s add a method:

User.prototype.sayHi = function () {
  console.log(`Hi, I am ${this.name}`);
};

Now:

user1.sayHi(); // Hi, I am Dhurandar 

Even though sayHi is not inside user1, it works because:

user1.__proto__ points to User.prototype

This is called the prototype chain.


Instances Created from Constructors

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

const user1 = new User("Kajol", 25);
const user2 = new User("Rahul", 30);

Both are different objects:

console.log(user1 === user2); // false

But they share the same prototype:

console.log(user1.__proto__ === user2.__proto__); // true

Standout Insight: Why Not Just Use Classes?

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

But under the hood, it’s still using the same mechanism.

Understanding new helps us:

  • Debug better

  • Understand prototypes deeply

  • Write cleaner JavaScript

2 views