How new keyword work in JavaScript
In JavaScript, the new
keyword is used to create an instance of an object from a constructor function or a class. When you use the new
keyword, it performs several actions behind the scenes to initialize the newly created object. Here's how the new
keyword works step by step.
How new
Works ?
Creates a new empty object: When you call a function with
new
, it creates an empty object that will eventually be linked to the prototype of the constructor function.Sets the prototype of the new object: The newly created object's
__proto__
(prototype) is linked to the constructor function'sprototype
property. This allows the new object to inherit methods and properties from the constructor’s prototype.Binds
this
to the new object: Inside the constructor function, thethis
keyword is bound to the newly created object. This allows the constructor to assign properties and methods tothis
, which ultimately references the new object.Executes the constructor function: The constructor function is executed with
this
bound to the new object. Any properties or methods defined in the constructor function will be assigned to the new object.Returns the new object: By default, the
new
keyword returns the new object unless the constructor explicitly returns a different object.
Example: Using new
with a Constructor Function
function Car(brand, model) {
this.brand = brand;
this.model = model;
this.drive = function() {
console.log(`Driving a ${this.brand} ${this.model}`);
};
}
const myCar = new Car('Toyota', 'Corolla');
myCar.drive(); // Output: Driving a Toyota Corolla
Here’s what happens when new Car('Toyota', 'Corolla')
is called:
Step 1: An empty object is created:
{}
.Step 2: The empty object’s
__proto__
is set toCar.prototype
.Step 3:
this
is bound to the new object, and the propertiesbrand
andmodel
are added to the new object.Step 4: The
Car
function runs, and thedrive()
method is added to the object.Step 5: The newly created object (
myCar
) is returned, which now hasbrand
,model
, anddrive()
.
Example: Using new
with ES6 Classes
In ES6, classes provide a cleaner syntax for creating objects using new
. However, behind the scenes, they work similarly to constructor functions.
class Car {
constructor(brand, model) {
this.brand = brand;
this.model = model;
}
drive() {
console.log(`Driving a ${this.brand} ${this.model}`);
}
}
const myCar = new Car('Tesla', 'Model 3');
myCar.drive(); // Output: Driving a Tesla Model 3
In this example:
The
new
keyword is used to create an instance of theCar
class.It follows the same process of creating a new object, binding
this
, setting up the prototype, and returning the new object.
Returning Values from Constructors
Normally, a constructor function returns the newly created object. However, if you explicitly return an object from the constructor, that object will be returned instead of the new instance.
function Person(name) {
this.name = name;
// Explicitly returning an object
return {
age: 30
};
}
const person = new Person('John');
console.log(person); // Output: { age: 30 }
In this case, even though we passed the name 'John'
, the returned object is { age: 30 }
because the constructor returned an object explicitly. If no object is explicitly returned, the new object created with new
is returned.
What Happens Without new
?
If you call a constructor function without new
, this
will refer to the global object (in non-strict mode), or be undefined
(in strict mode), which can lead to unexpected behavior.
function Car(brand) {
this.brand = brand;
}
const car1 = new Car('Toyota'); // Works as expected
console.log(car1.brand); // Output: Toyota
const car2 = Car('Honda'); // Forgetting `new`
console.log(car2); // Output: undefined (because the function returns nothing)
console.log(window.brand); // Output: Honda (in non-strict mode, `this` refers to the global object)
Without new
, the Car
function will run like a normal function, and this.brand
will point to the global object (window
in browsers). This is why using new
is crucial when creating instances with constructors.
Summary
The new
keyword in JavaScript:
Creates a new object.
Links the new object's prototype to the constructor's
prototype
.Binds
this
to the new object within the constructor.Executes the constructor to initialize the object.
Returns the new object by default.
This is the process that allows you to create new objects in JavaScript based on constructors or classes.
Subscribe to my newsletter
Read articles from Bhupendra directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Bhupendra
Bhupendra
I'm a passionate software developer with a strong foundation in JavaScript, TypeScript, Node.js, and React. I've honed my skills in full-stack development and building scalable, user-friendly applications. I'm driven by creating innovative solutions that solve real-world problems and enhance user experiences. I'm a quick learner, constantly updating myself with the latest industry trends and best practices. Beyond technical skills, I value collaboration, problem-solving, and maintaining a growth mindset. I'm excited to contribute my expertise to a dynamic team and make a positive impact through technology.