Skip to content

OOP in JS (classes, inheritance, polymorphism)

  • Classes are blueprint for creating objects. They support constructors, methods and properties.
  • Example:
class Person {
constructor(name, age){
this.name = name;
this.age = age
}
greet() => {
console.log(`My name is ${this.name} and I'm ${this.age} yrs old.`)
}
}
const person = new Person('Sonam', '26')
person.greet() // My name is Sonam and I'm 26 yrs old.
  • One class can extend another, reusing its properties and methods.
  • Example:
class Developer extends Person {
constructor(name, age, role){
super(name, age) // call parent constructor
this.role = role
}
code(){
console.log(`${this.name} is coding as a ${this.role}`)
}
}
const dev = new Developer('Sonam', 26, 'Full Stack Developer')
dev.code() // Sonam is coding as a Full Stack Developer
  • Methods can be overriden in child classes to provide specialized behaviour.
  • 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 animals = [new Dog(), new Cat(), new Animal()];
animals.forEach(a => a.speak());
// ๐Ÿถ The dog barks.
// ๐Ÿฑ The cat meows.
// The animal makes a sound.
  • ๐Ÿ‘‰ Hiding internal details and exposing only whatโ€™s necessary.

    • Achieved using class fields (#private) and getter/setter methods.

    • Eg:

      class BankAccount {
      #balance = 0; // private property
      deposit(amount) {
      if (amount > 0) this.#balance += amount;
      }
      withdraw(amount) {
      if (amount <= this.#balance) this.#balance -= amount;
      else console.log("Insufficient balance");
      }
      get balance() { // getter
      return this.#balance;
      }
      }
      const acc = new BankAccount();
      acc.deposit(100);
      acc.withdraw(50);
      console.log(acc.balance); // 50
      // console.log(acc.#balance); โŒ Error (private)
    • โœ… Keeps sensitive data safe and controlled.

  • ๐Ÿ‘‰ Hiding complex implementation and showing only the essential functionality.

    • In JS, done via abstract-like base classes or interfaces (TS).
    • Eg:
    class Vehicle {
    startEngine() {
    throw new Error("startEngine() must be implemented");
    }
    }
    class Car extends Vehicle {
    startEngine() {
    console.log("๐Ÿš— Car engine started");
    }
    }
    const c = new Car();
    c.startEngine(); // ๐Ÿš— Car engine started
    • โœ… Forces subclasses to implement required methods, hiding complexity.
PillarMeaningExample in JS
EncapsulationHide internal detailsPrivate fields #balance
AbstractionShow only essentialsAbstract base Vehicle
InheritanceReuse functionalityclass Dog extends Animal
PolymorphismSame method, different behaviorspeak() in Dog/Cat/Bird
  • Class -> Blueprint for object.
  • Inheritance -> Reuse properties/methods via extends
  • Polymorphism -> Same method, different behaviour in subclasses.
  • Classes are used for models (like User, Product).
  • Inheritance for specialized classes (like AdminUser extends User).
  • Polymorphism for overriding behavior (like render() in React components).
  • Encapsulation โ†’ Hide DB logic inside classes (e.g., UserModel).
  • Abstraction โ†’ Base service classes, interfaces.