Skip to main content

Command Palette

Search for a command to run...

The new Keyword in JavaScript: A Complete Beginner-Friendly Guide

Published
3 min read

If you've ever seen code like this:

function Person(name) {
  this.name = name;
}

const user = new Person("Sayantan");

You might have wondered — what exactly does new do here?

This article will break it down step-by-step so you truly understand how object creation works in JavaScript.


🔹 What Does the new Keyword Do?

The new keyword is used to create instances of objects from a constructor function.

In simple terms:

It turns a normal function into a blueprint for creating objects.

Without new, the function behaves like a regular function. With new, it becomes a constructor.


🔹 Constructor Functions

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

  • It starts with a capital letter

  • It is used with the new keyword

Example:

function Car(brand, model) {
  this.brand = brand;
  this.model = model;
}

Now we can create objects like this:

const car1 = new Car("Toyota", "Fortuner");
const car2 = new Car("Tesla", "Model 3");

Each object created is called an instance.


🔹 What Happens Internally When You Use new?

This is the most important part.

When you run:

const car1 = new Car("Toyota", "Fortuner");

JavaScript performs 4 internal steps:


✅ Step 1: Create a New Empty Object

const obj = {};

obj.__proto__ = Car.prototype;

This is what enables prototype inheritance.


✅ Step 3: Bind this to the New Object

this = obj;

Inside the constructor:

this.brand = "Toyota";
this.model = "Fortuner";

✅ Step 4: Return the Object

return obj;

So finally:

car1 = {
  brand: "Toyota",
  model: "Fortuner"
}

Every function in JavaScript has a prototype property.

function Person(name) {
  this.name = name;
}

Person.prototype.sayHello = function () {
  console.log("Hello, I am " + this.name);
};

Now:

const p1 = new Person("Sayantan");
p1.sayHello();

Why does this work?

Because:

p1.__proto__ === Person.prototype  // true

So JavaScript looks up the prototype chain when a method is not found directly on the object.


🔹 Instances Created from Constructors

Each object created using new:

  • Has its own copy of properties

  • Shares methods via prototype

Example:

function Student(name) {
  this.name = name;
}

Student.prototype.study = function () {
  console.log(this.name + " is studying");
};

const s1 = new Student("Amit");
const s2 = new Student("Rahul");

Key Points:

  • s1 and s2 are different objects

  • But both share the same study() method (memory efficient)


🔹 Without new (Common Mistake)

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

const u1 = User("Sayantan"); // ❌

Problems:

  • this refers to global object (or undefined in strict mode)

  • No object is created properly

2 views