JavaScript classes provide a clear, concise syntax to create objects and manage inheritance. They act as blueprints for objects, defining properties and behaviors.
What is a Class?
A class is a template for creating objects. It encapsulates data (properties) and functions (methods) that operate on that data.
Constructor Method
The constructor is a special method inside a class. It runs automatically when you create a new instance, setting initial property values.

💡 Constructor Basics
Every class can have only one constructor method. It is called when you create an object with new.
Creating a Class with a Constructor
Here’s the simplest way to create a class with a constructor that initializes properties:
📌 Deep Dive: Defining a Class and Constructor
class Car {
constructor(make, model) {
this.make = make; // Property 'make' initialized
this.model = model; // Property 'model' initialized
}
}
Instantiating Objects
Use the new keyword to create an instance of the class and pass arguments to the constructor:
📌 Deep Dive: Creating an Instance
const myCar = new Car('Toyota', 'Corolla');
console.log(myCar.make); // Output: Toyota
console.log(myCar.model); // Output: Corolla
Corolla
Key Points About Classes & Constructors
- Classes are syntactic sugar over JavaScript's prototype-based inheritance.
- The
constructormethod initializes new objects. - If no constructor is defined, a default empty constructor is used.
- Use
thisto assign properties inside the constructor.
| Class Syntax | Constructor Function |
|---|---|
| Cleaner, easier to read | Traditional, verbose |
Supports extends for inheritance | Uses prototypes explicitly |
Must use constructor method | Function itself acts as constructor |
⚠️ Important
Calling a class without new will throw an error. Always use new when instantiating.
Adding Methods to a Class
Methods can be declared inside the class but outside the constructor. They become part of the object's prototype.
📌 Deep Dive: Adding Methods
class Car {
constructor(make, model) {
this.make = make;
this.model = model;
}
getDescription() {
return `${this.make} ${this.model}`;
}
}
const myCar = new Car('Honda', 'Civic');
console.log(myCar.getDescription()); // Honda Civic
💡 Summary
Classes organize code by combining properties and methods. Constructors set initial values, and methods define behavior.
Quick Knowledge Check
Test what you just learned
Question 1 of 2
What does the constructor method do in a class?
Question 2 of 2
How do you create an instance of a class?
Loading results...