Understanding Object-Oriented Programming in JavaScript
CSE Under grad. || Trying to be a better developer each day || Consistency is the key
Intro
Object-Oriented Programming (OOP) is basically a way to organize code by thinking about things as "objects" that have their own data and behaviors. Instead of just writing random functions and variables everywhere, you bundle related stuff together — like how in real life a car has color, speed, and can drive().The big idea: reusability and structure. You create a blueprint once, then make as many copies (objects) as you want.
Real-world analogy:
Think of a Car blueprint (like engineering drawing). The blueprint says: every car has color, model, and can honk().
Then you build actual cars from it: my red Toyota that honks, your blue Honda that honks differently maybe.
Blueprint = class
Actual cars = objects (instances)In JavaScript, we use classes (introduced in ES6) to make this blueprint.
What is a class in JS :
A class is like a template or factory for creating objects with the same properties and methods.Creating a class and objects
class Car {
// constructor runs when you make a new object
constructor(make, model, color) {
this.make = make;
this.model = model;
this.color = color;
this.isRunning = false;
}
// method inside class
startEngine() {
this.isRunning = true;
console.log(`\({this.make} \){this.model} is vroom vroom!`);
}
honk() {
console.log("Beep beep!");
}
}
Making objects (instances)
const myCar = new Car("Toyota", "Corolla", "red");
const yourCar = new Car("Honda", "Civic", "blue");
myCar.startEngine(); // Toyota Corolla is vroom vroom!
yourCar.honk(); // Beep beep!
console.log(myCar.color); // red
Same blueprint, different cars. Super reusable ...
Basic idea of encapsulation:
Encapsulation means keeping the data (properties) and actions (methods) together inside the object, and kinda hiding the messy details.
Like, you dont need to know how the engine works inside to drive the car — you just call startEngine().
In JS its not super strict (no private by default till recently), but using methods to interact with data is the encapsulation vibe.
class Student {
constructor(name, age) {
this.name = name;
this.age = age;
}
printDetails() {
console.log(`Name: \({this.name}, Age: \){this.age}`);
}
}
const student1 = new Student("Rahul", 19);
const student2 = new Student("Sneha", 20);
const student3 = new Student("Aman", 21);
student1.printDetails(); // Name: Rahul, Age: 19
student2.printDetails(); // Name: Sneha, Age: 20
student3.printDetails(); // Name: Aman, Age: 21
Made three students from one class — clean and no repeating code. . Classes make code organised, reusable, and easier to think about big projects. No need for fancy inheritance yet, just start with simple classes like Person/Car/Student.