But when your project starts growing… objects alone aren’t enough.
That’s where Classes & OOP (Object-Oriented Programming) step in.
Let’s break it down in a practical, developer-friendly way — no textbook talk.
🚀 What is OOP in JavaScript?
Object-Oriented Programming is simply a way of structuring code using:
- Objects
- Reusable blueprints (classes)
- Encapsulation
- Inheritance
Instead of writing scattered logic, you group related data and behavior together.
Think of it like this:
👉 A class is a blueprint.
👉 An object is the actual thing created from that blueprint.
🏗️ Creating a Class in JavaScript
Here’s the simplest example:
class User {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
return `Hi, I'm ${this.name}`;
}
}
Now create an object (instance):
const user1 = new User("Arun", 25);
console.log(user1.greet());
That’s it. Clean. Organized. Reusable.
🔑 The Constructor Method
The constructor() runs automatically when you create a new object.
const user2 = new User("Meena", 30);
It initializes your object with values.
No constructor? JavaScript adds a default empty one.
🧠 Methods Inside Classes
Functions inside classes are called methods.
class Calculator {
add(a, b) {
return a + b;
}
}
Notice:
- No
functionkeyword - No commas between methods
Cleaner than object literals for structured logic.
🔒 Encapsulation (Protecting Data)
Modern JavaScript supports private fields using #.
class BankAccount {
#balance = 0;
deposit(amount) {
this.#balance += amount;
}
getBalance() {
return this.#balance;
}
}
Now #balance cannot be accessed directly.
This prevents accidental misuse.
🧬 Inheritance (Reusing Logic)
One of the most powerful OOP features.
class Animal {
speak() {
return "Animal makes a sound";
}
}
class Dog extends Animal {
bark() {
return "Woof!";
}
}
const dog = new Dog();
console.log(dog.speak());
console.log(dog.bark());
Dog now has access to everything inside Animal.
That’s code reuse done right.
🧩 The super() Keyword
When using inheritance, super() calls the parent constructor.
class Person {
constructor(name) {
this.name = name;
}
}
class Developer extends Person {
constructor(name, language) {
super(name);
this.language = language;
}
}
Without super(), the child class won’t work properly.
🎯 When Should You Use Classes?
Use classes when:
- You need multiple similar objects
- Your logic is getting complex
- You want clean architecture
- You’re building larger applications
Avoid overusing classes for tiny scripts.
⚡ Common Mistakes Developers Make
❌ Forgetting new keyword
❌ Using arrow functions as class methods incorrectly
❌ Overcomplicating simple logic with OOP
❌ Ignoring private fields for sensitive data
Keep it simple.
🚀 Best Practice Summary
✅ Use classes for scalable, reusable structures
✅ Keep constructors minimal
✅ Prefer methods over inline logic
✅ Use inheritance only when it truly makes sense
✅ Don’t over-engineer small features
0 Comments