The new Keyword with Classes
In this lesson, you'll learn what happens under the hood when you use new to create an instance from a class.
What Happens When You Call new ClassName()
When you write new before a class, JavaScript performs three automatic steps:
- Creates a new empty object – A fresh object is born in memory
- Runs the constructor method – Your
constructor()function executes, withthisbound to that new object - Returns the object automatically – The newly created object is returned (you don't write
return)
Think of it like ordering a custom cake: the bakery (JavaScript) prepares a blank cake base (creates the object), decorates it according to your specifications (runs the constructor), and hands you the finished product (returns it).
The Process in Action
class Car {
constructor(brand, model) {
this.brand = brand; // Step 2: Setting properties on the new object
this.model = model;
}
drive() {
console.log(`${this.brand} ${this.model} is driving`);
}
}
// Step 1: new creates an empty object
// Step 2: constructor runs, adding brand and model
// Step 3: The completed object is returned and stored in myCar
const myCar = new Car('Toyota', 'Camry');
console.log(myCar.brand); // 'Toyota'
myCar.drive(); // 'Toyota Camry is driving'
Without new, the constructor won't create an object for you—you'd just be calling a function that tries to set properties on nothing.
Key Takeaway: The new keyword creates an object, executes the class constructor with this pointing to that object, and automatically returns the finished instance—no manual return needed.