🔄 Polymorphism in JavaScript (OOP)

Last Updated: 24th October 2025


Polymorphism means “many forms”.
In JavaScript OOP, it allows objects of different classes to be treated the same way or methods to behave differently depending on the object.

Hinglish Tip 🗣: Jaise aap ek button pe click karte ho, lekin har app me action alag hota hai. Yaha “click” ek hi naam ka method hai, par har object ke liye behavior alag hai. Yehi hai polymorphism.


1. Method Overriding

  • Child class changes the behavior of parent method.
  • We already saw this in Inheritance.
class Vehicle {
  start() {
    console.log("Vehicle started");
  }
}

class Car extends Vehicle {
  start() {
    console.log("Car started");
  } // overridden
}

const v = new Vehicle();
const c = new Car();

v.start(); // Vehicle started
c.start(); // Car started

Hinglish Tip 🗣: Same method name, different behavior → this is runtime polymorphism.


2. Method Overloading

  • Same method name with different parameters.
  • The method with different parameters is called overloaded.
class Calculator {
  add(a, b) {
    return a + b;
  }

  add(a, b, c) {
    return a + b + c;
  } // overloaded
}

const calc = new Calculator();

console.log(calc.add(1, 2)); // 3
console.log(calc.add(1, 2, 3)); // 6

Hinglish Tip 🗣: Same method name, different parameters → this is compile-time polymorphism.


3. Operator Polymorphism

Same operator behaves differently for different data types.

console.log(5 + 3); // 8 (numbers → addition)
console.log("5" + "3"); // "53" (strings → concatenation)

Hinglish Tip 🗣: + operator ka behavior depend karta hai datatype pe.


4. Duck Typing (Dynamic Polymorphism)

In JS, if an object has the required method/property, it can be used without checking type.

function makeSound(animal) {
  animal.sound();
}

const dog = { sound: () => console.log("Woof!") };
const cat = { sound: () => console.log("Meow!") };

makeSound(dog); // Woof!
makeSound(cat); // Meow!

Hinglish Tip 🗣: “If it walks like a duck and quacks like a duck, it’s a duck.” → method exists, so it works.


💡 Quick Practice

  • Create Shape class with method area().
  • Create Square and Circle classes extending Shape, override area() with their formulas.
  • Test polymorphism by creating an array [new Square(5), new Circle(3)] and calling area() on each object.
  • Exercise