Object Oriented Programming (OOP)

- Understanding Object-Oriented Programming (OOP) in JavaScript
JavaScript is one of the most powerful and flexible programming languages used for web development. One of its core concepts that developers must understand is Object-Oriented Programming (OOP). OOP is a programming paradigm that allows developers to write cleaner, more maintainable, and reusable code. In this article, we will explore the basics of OOP in JavaScript and show how it can be used to structure your code better.
- What is Object-Oriented Programming (OOP)?
Object-Oriented Programming is a style of programming that is based on the concept of objects. These objects contain both data (also known as properties) and functions (also known as methods). OOP provides a way to organize and structure your code in a way that reflects the real-world entities and their behaviors.
In simple terms, OOP enables you to model the real world using software objects. For example, if you are building a system to track employees in a company, you might have an Employee object that contains data like name, age, and position. It could also have methods like getSalary() and updatePosition().
By using OOP, you can write reusable code, making it easier to manage and update. It also helps you structure large programs into manageable chunks, which can be independently modified without affecting other parts of the program.

- Why Use OOP in JavaScript?
- Encapsulation: By organizing your data and functions into objects, you can ensure that the internal details of the object are hidden from the outside world. This makes the code more modular and easier to maintain.
- Reusability: Once an object is defined, it can be reused across different parts of the application, saving you time and reducing redundancy.
- Scalability: OOP allows you to easily scale and extend your applications by adding new classes or objects, without the need to rewrite large sections of code.
- Maintainability: Since OOP organizes code into smaller, self-contained modules (objects), it’s much easier to manage and debug in the long run.
- The Four Pillars of OOP
There are four major principles or pillars that define the concept of OOP. These principles are key to writing clean, effective, and scalable OOP code in JavaScript.
1. Encapsulation
Encapsulation is the process of bundling the data (properties) and the functions (methods) that work on the data into a single unit, called an object. This prevents external parts of the program from directly accessing or modifying the object’s internal state, thus ensuring the data remains safe and consistent.
Here, name, age, and position are encapsulated within the Employee object, and any interaction with this data must be done via methods like getDetails() and updatePosition().
Example:
class Employee {
constructor(name, age, position) {
this.name = name;
this.age = age;
this.position = position;
}
// Method to update position
updatePosition(newPosition) {
this.position = newPosition;
}
// Method to get employee details
getDetails() {
return `Name: ${this.name}, Age: ${this.age}, Position: ${this.position}`;
}
}
const emp = new Employee("John Doe", 30, "Software Engineer");
emp.updatePosition("Senior Developer");
console.log(emp.getDetails());
2. Inheritance
Inheritance allows a class (child class) to inherit properties and methods from another class (parent class). This helps you reuse existing code and extends it with new functionality without modifying the original code.
Example:
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
greet() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
class Employee extends Person {
constructor(name, age, position) {
super(name, age); // Calling the parent class constructor
this.position = position;
}
work() {
console.log(`${this.name} is working as a ${this.position}`);
}
}
const emp = new Employee("Alice", 28, "Manager");
emp.greet(); // Inherited from Person class
emp.work(); // Method specific to Employee class
In this example, Employee inherits the greet method from the Person class and adds its own work method.
3. Polymorphism
Polymorphism means “many shapes” and it allows one method to operate on different types of objects. Essentially, polymorphism allows the same method to behave differently based on the object it is operating on.
Example:
class Animal {
speak() {
console.log("The animal makes a sound");
}
}
class Dog extends Animal {
speak() {
console.log("The dog barks");
}
}
class Cat extends Animal {
speak() {
console.log("The cat meows");
}
}
const dog = new Dog();
const cat = new Cat();
dog.speak(); // The dog barks
cat.speak(); // The cat meows
In this case, both Dog and Cat override the speak method of Animal, which is an example of polymorphism. The same method name results in different behaviors based on the class.
4. Abstraction
Abstraction is the concept of hiding the complex implementation details of an object and only exposing the necessary information to the user. Abstraction helps simplify complex systems by focusing on high-level functionalities rather than low-level details.
Example:
class Car {
constructor(brand) {
this.brand = brand;
}
startEngine() {
console.log("Starting the engine...");
this._performStart();
}
// Private method (simulated with a naming convention)
_performStart() {
console.log("Engine is running now.");
}
}
const myCar = new Car("Tesla");
myCar.startEngine(); // User only interacts with startEngine, hiding complexity
In this case, the user interacts with the startEngine() method, which hides the complex internal process through the private method _performStart().

- Implementing OOP in JavaScript
JavaScript supports OOP principles through different techniques for creating objects and classes. Let’s look at three common ways to implement OOP in JavaScript:
1. Object Literals
Before the introduction of ES6 classes, JavaScript objects were created using object literals, where properties and methods were defined directly within an object.
Example:
const car = {
brand: "Toyota",
startEngine: function() {
console.log("Engine started.");
}
};
car.startEngine();
2. Constructor Functions
Constructor functions are used to create multiple instances of an object. Constructor functions were the primary way to create objects in JavaScript before ES6 classes.
Example:
function Car(brand) {
this.brand = brand;
}
Car.prototype.startEngine = function() {
console.log(`${this.brand} engine started.`);
};
const myCar = new Car("Honda");
myCar.startEngine();
3. ES6 Classes
With ES6, JavaScript introduced the class syntax, which makes object creation easier and more intuitive. It’s a more formal way to work with objects and their prototypes.
Example:
class Car {
constructor(brand) {
this.brand = brand;
}
startEngine() {
console.log(`${this.brand} engine started.`);
}
}
const myCar = new Car("Ford");
myCar.startEngine();
Classes offer a more structured and modern approach to object creation, and are now the preferred way to implement OOP in JavaScript.
- Conclusion
Object-Oriented Programming is a powerful approach to writing code in JavaScript. By understanding and implementing the four pillars of OOP—encapsulation, inheritance, polymorphism, and abstraction—developers can write more efficient, scalable, and maintainable applications.
JavaScript offers multiple ways to implement OOP, including object literals, constructor functions, and ES6 classes. By mastering these techniques, developers can structure their code in a way that makes it easier to manage and extend over time.
Learning OOP is an essential step for any JavaScript developer, especially if you want to build large, complex applications. By properly using OOP, you can build more organized and efficient code, which will save you time and effort in the long run.