Object-Oriented Programming (OOP) in JavaScript

What is OOP?

OOP (Object-Oriented Programming) is a programming paradigm where programs are designed using objects — which can hold data (properties) and methods (functions).

Why Use OOP?

When and Where to Use?

OOP Key Concepts in JavaScript

What is a Class?

A Class is a blueprint to create objects with predefined properties and methods.

Example:

class Car {
  constructor(brand, model) {
    this.brand = brand;
    this.model = model;
  }

  displayInfo() {
    return `Car: ${this.brand} ${this.model}`;
  }
}

What is an Object?

An Object is an instance of a Class. It holds actual values for the properties defined by the class.

Creating and Accessing Object:

const car1 = new Car('Toyota', 'Corolla');
console.log(car1.displayInfo()); // Output: Car: Toyota Corolla

Encapsulation

Encapsulation hides internal details and exposes only necessary parts.

class BankAccount {
  #balance = 0; // private field

  deposit(amount) {
    if(amount > 0) this.#balance += amount;
  }

  getBalance() {
    return this.#balance;
  }
}

const acc = new BankAccount();
acc.deposit(1000);
console.log(acc.getBalance()); // Output: 1000

Inheritance

Inheritance allows a class to acquire properties and methods from another class.

class Vehicle {
  move() {
    return 'Moving...';
  }
}

class Bike extends Vehicle {
  ringBell() {
    return 'Ring Ring!';
  }
}

const myBike = new Bike();
console.log(myBike.move()); // Moving...
console.log(myBike.ringBell()); // Ring Ring!

Polymorphism

Polymorphism allows objects to be treated as instances of their parent class while still calling their own methods.

class Animal {
  speak() {
    return 'Some sound';
  }
}

class Dog extends Animal {
  speak() {
    return 'Bark';
  }
}

const pet = new Dog();
console.log(pet.speak()); // Bark
Note: In real-world applications like React, Vue, and Node.js, OOP is used heavily to manage state, build components, and structure backend logic.

Summary