The new Keyword in JavaScript
CSE Under grad. || Trying to be a better developer each day || Consistency is the key
Intro
One of the most important but sometimes confusing concepts in JavaScript — the new keyword. I remember being confused about what exactly happens when we use new in front of a function. Once I understood it properly, a lot of things clicked.
Let’s break it down simply.
What Does the new Keyword Do?
The new keyword is used to create a new object instance from a constructor function. It basically tells JavaScript: “Create a new object and set it up according to this constructor.”
Constructor Functions
A constructor function is a normal function that is designed to be called with new. By convention, we name them with a capital letter.
function Person(name, age) { this.name = name; this.age = age; }
const sam = new Person("Sam", 28); console.log(sam);
// Person { name: "Sam", age: 28 }
What Happens When You Use new?
When you write new Person("Sam", 28), JavaScript does these four things automatically:Creates a new empty object {}
Links the new object’s prototype to the constructor’s prototype (proto) Calls the constructor function with this bound to the new object Returns the new object (unless you explicitly return something else)
Simple Example
function Car(brand, model) { this.brand = brand; this.model = model; this.start = function() { console.log(\({this.brand} \){this.model} is starting...); }; }
const myCar = new Car("Toyota", "Camry"); const anotherCar = new Car("Honda", "City");
myCar.start(); // Toyota Camry is starting... console.log(myCar.brand); // Toyota
Both myCar and anotherCar are independent instances created from the same constructor.
The Prototype Connection
When you use new, the new object gets linked to the constructor’s prototype. This is why methods defined on Constructor.prototype are available to all instances.js
Person.prototype.greet = function() { console.log(Hi, I'm ${this.name}); };
sam.greet(); // Hi, I'm Sam
Conclusion
new creates a new object instance It automatically sets up the prototype chain this inside the constructor refers to the newly created object Every time you call a constructor with new, you get a fresh new object
Understanding new is very important because it forms the foundation of how objects and classes work in JavaScript (even the modern class syntax uses it behind the scenes).