The new Keyword in JavaScript (Simple Guide for Beginners)
The new keyword in JavaScript is used to create objects from constructor functions.
It may look simple, but it performs multiple steps behind the scenes. Understanding this helps you write better and more structured code.
What the new Keyword Does
When you use new, JavaScript creates a new object and links it with a constructor function.
Example:
function User(name, age) {
this.name = name;
this.age = age;
}
const user1 = new User("Ram", 22);
console.log(user1);
Here, new User() creates a new object using the User function.
Constructor Functions
A constructor function is a normal function used to create objects.
By convention, constructor names start with a capital letter.
function Car(brand) {
this.brand = brand;
}
const car1 = new Car("Toyota");
Each time you call new Car(), a new object is created.
Object Creation Process (Step by Step)
When you use new, JavaScript does the following steps:
Creates an empty object
Sets
thisto point to that objectLinks the object to the constructor’s prototype
Executes the constructor function
Returns the new object
Constructor to Instance Flow
The constructor builds the object and returns an instance.
How new Links Prototypes
Every constructor function has a prototype.
Objects created with new are linked to that prototype.
Example:
function Person(name) {
this.name = name;
}
Person.prototype.greet = function () {
console.log("Hello " + this.name);
};
const p1 = new Person("Ram");
p1.greet();
Even though greet is not inside the object, it works because of prototype linking.
Prototype Linking Visualization
The object is connected to the constructor’s prototype.
Instances Created from Constructors
Each object created using new is called an instance.
Example:
function Animal(type) {
this.type = type;
}
const a1 = new Animal("Dog");
const a2 = new Animal("Cat");
Here:
a1anda2are instancesBoth are created from the same constructor
Why new is Important
Helps create multiple objects easily
Reuses structure using constructors
Supports prototype-based inheritance
Simple Mental Model
Think of a constructor as a blueprint.
Using new creates a real object from that blueprint.
Conclusion
The
newkeyword creates objects from functionsIt performs multiple steps internally
It links objects to prototypes
It helps create reusable and structured code
Understanding new is important for mastering JavaScript fundamentals and object-oriented concepts.