Classes & Objects in JavaScript
Diagram explaining JavaScript classes and objects
In JavaScript, classes and objects are foundational to writing modular and reusable code using Object-Oriented Programming (OOP) principles. They allow developers to model real-world entities, group functionality, and maintain cleaner code.
A class is a blueprint for creating objects. Introduced in ES6 (ECMAScript 2015), the class
syntax provides a more readable and structured way to work with constructor functions and prototypes under the hood.
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hi, I'm ${this.name} and I'm ${this.age} years old.`);
}
}
constructor()
is a special method used to initialize object properties.
greet()
is an instance method available to all objects created from the class.
An object is an instance of a class. It represents a specific entity created using the structure defined by the class.
const john = new Person("John", 30);
john.greet(); // Hi, I'm John and I'm 30 years old.
Here, john
is an object created using the Person
class — it has access to both the properties and methods defined in that class.
Defined in the constructor()
and unique to each object.
Functions defined inside the class and shared across instances via prototype.
this
KeywordRefers to the object being created or used.
Classes in JavaScript support inheritance using the extends
and super
keywords.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a sound`);
}
}
class Dog extends Animal {
speak() {
console.log(`${this.name} barks`);
}
}
const dog = new Dog("Buddy");
dog.speak(); // Buddy barks
Cleaner and more structured code.
Easier inheritance and method sharing.
Better code organization and maintainability.
Syntactic sugar over prototype-based inheritance.
Classes and objects are essential parts of modern JavaScript development. Classes provide the structure, while objects are the actual data instances. With ES6 class syntax, JavaScript makes OOP more accessible, letting developers build cleaner, more maintainable code.