DEV Community

Hiral
Hiral

Posted on

The new Keyword in JavaScript

If you've ever written new Person("Alice") and wondered what's actually happening behind the scenes — this post is for you.

what is constructor function?
A constructor function is just a regular function, but by convention we capitalize its name to signal it should be called with new.

function Person(name, age) {
  this.name = name;
  this.age  = age;
}
Enter fullscreen mode Exit fullscreen mode

Inside it, this refers to the new object being built. That's the key idea.
What does new actually do?
When you write:

const alice = new Person("Alice", 30);
Enter fullscreen mode Exit fullscreen mode

JavaScript silently does four things for you:

  1. Creates a brand-new empty object
// internally: const this = {};
Enter fullscreen mode Exit fullscreen mode

2.Links it to the constructor's prototype

// internally: this.__proto__ = Person.prototype;
Enter fullscreen mode Exit fullscreen mode

This is how alice can call methods like greet() even though they aren't stored on alice itself.
3.Runs the constructor body with this as that new object

this.name = "Alice";
Enter fullscreen mode Exit fullscreen mode

4.Returns the object automatically.You don't need a return statement — new handles it

Putting methods on the prototype
Instead of copying a method into every instance (wasteful!), you add it once to the prototype:

Person.prototype.greet = function() {
  console.log("Hi, I'm " + this.name);
};

const alice = new Person("Alice", 30);
const bob   = new Person("Bob",   25);

alice.greet(); // "Hi, I'm Alice"
bob.greet();   // "Hi, I'm Bob"
Enter fullscreen mode Exit fullscreen mode

Both alice and bob share the same greet function. Neither instance stores a copy — they just look up the chain.
The prototype chain

When you call alice.greet(), JavaScript searches in this order:

Does alice have greet directly? → No
Does alice.proto (= Person.prototype) have greet? → Yes! Use it.

This chain of lookups is called the prototype chain.

Summary:

  1. A constructor function is a blueprint for creating objects.
  2. new creates an empty object, links its prototype, runs the constructor, and returns the result.
  3. Own data lives on the instance; shared methods live on the prototype.
  4. When a property isn't found on the instance, JavaScript walks up the prototype chain to find it.

Top comments (0)