JavaScript Notes
Master polymorphism in JavaScript with method overriding, duck typing, runtime polymorphism, real-world examples, common mistakes, and interview Q&A. beginner-friendly.
Polymorphism means "many forms" — the ability to call the same method on different objects and get different behavior based on the object's type. It is the fourth pillar of OOP and the key to writing clean, extensible code.
With polymorphism, you write code that works with a general type (e.g., Shape), and it automatically handles all specific types (Circle, Square, Triangle) correctly — even types added months later.
📊 Polymorphism Diagram
💻 Example 1 — Method Overriding (Subtype Polymorphism)
A blue Circle with area 78.54 A green Rectangle with area 24.00 A red Triangle with area 12.00 Total area: 114.54
💻 Example 2 — Duck Typing (JavaScript's Unique Polymorphism)
JavaScript does not require a formal inheritance hierarchy for polymorphism. If an object has the right method, it works — this is called duck typing ("if it quacks like a duck, it's a duck").
[TEXT] Processing order #42
[TEXT] Order #42 complete
[JSON] {"msg":"Processing order #43","ts":1749686400000}
[JSON] {"msg":"Order #43 complete","ts":1749686400001}
All orders processed💻 Example 3 — Polymorphism with Payment Methods
💳 Charging ₹1500 to card ****3456 Receipt: ₹1500 paid via CreditCard --- 📱 Sending ₹800 via UPI to student@upi Receipt: ₹800 paid via UPI --- 🏦 Processing ₹3000 via HDFC NetBanking Receipt: ₹3000 paid via NetBanking ---
📋 Types of Polymorphism in JavaScript
| Type | How it works in JS | Example |
|---|---|---|
| Subtype / Runtime | Method overriding via extends | shape.area() calls Circle or Rectangle's version |
| Duck Typing | Any object with the right method works | Any object with .log() works as a logger |
| Ad-hoc (overloading) | Simulate with default params / conditionals | add(a, b, c = 0) works for 2 or 3 args |
| Parametric | Generic code via iteration | shapes.forEach(s => s.area()) |
⚠️ Common Mistakes
❌ Mistake 1 — Not Overriding the Method in the Subclass
class Animal { speak() { return "some sound"; } }
class Dog extends Animal { } // forgot to override speak()
const dog = new Dog();
console.log(dog.speak()); // "some sound" — not dog-specificsome sound
❌ Mistake 2 — Checking Type Instead of Using Polymorphism
// BAD — type-checking breaks the open/closed principle
function processShape(shape) {
if (shape instanceof Circle) return Math.PI * shape.radius ** 2;
if (shape instanceof Rectangle) return shape.width * shape.height;
// Need to add a new if for every new shape!
}
// GOOD — polymorphic call works for any shape, now and future
function processShape(shape) { return shape.area(); }❌ Mistake 3 — Calling a Method That Doesn't Exist on All Types
78.54 24 TypeError: item.area is not a function
🎯 Key Takeaways
- Polymorphism = same interface, different behavior depending on the object's type
- Method overriding (
extends+ same method name) is the classic polymorphism pattern - Duck typing in JavaScript means any object with the right method works — no class hierarchy needed
- Polymorphism enables the Open/Closed Principle: add new types without changing existing code
- Prefer polymorphism over
if/else instanceofchains — it's cleaner and more extensible - Use
super.method()to extend parent behavior rather than completely replacing it
❓ Interview Questions
Q1. What is polymorphism in JavaScript? > Polymorphism means "many forms." The same method name can produce different behavior depending on the object it is called on. In JavaScript, this is achieved through method overriding in subclasses and duck typing.
Q2. What is the difference between method overloading and method overriding? > Method overriding: a subclass redefines an inherited method with the same name. JavaScript supports this via extends. Method overloading (multiple methods with the same name but different parameters) is not natively supported in JavaScript — you simulate it with default parameters or arguments checking.
Q3. What is duck typing? > Duck typing means JavaScript doesn't require a formal class hierarchy for polymorphism. If an object has the method you're trying to call, it works — regardless of its class. "If it walks like a duck and quacks like a duck, it's a duck."
Q4. How does polymorphism follow the Open/Closed Principle? > The Open/Closed Principle states: code should be open for extension but closed for modification. With polymorphism, you can add a new Triangle class with its own area() without changing any code that calls shape.area(). The existing code just works.
Q5. What happens if a subclass does not override the parent method? > The parent's version of the method is called. This is valid — not all subclasses need to override. Override only when the child needs different behavior. If you want to enforce overriding, throw an error in the base class: throw new Error("Must implement method()").
Q6. Can you have polymorphism without inheritance in JavaScript? > Yes — through duck typing. Multiple unrelated objects can each implement a .draw() method and be used interchangeably. No shared class or interface needed. This is one of JavaScript's strengths over strictly typed languages.
Q7. What is runtime polymorphism? > Runtime polymorphism (also called dynamic dispatch) means the correct method to call is determined at runtime, not compile time. When you call shape.area() where shape could be a Circle or Rectangle, JavaScript decides which area() to call based on the actual object type at that moment.
Q8. How is constructor.name useful in polymorphism? > this.constructor.name returns the name of the class that created the object. In a base class method like describe(), using this.constructor.name dynamically picks up the subclass name, enabling the base class to display accurate type information without knowing the specific subclass.
Exam Focus
Revise definitions, diagrams, examples, and short-answer points for Polymorphism in JavaScript – Method Overriding, Duck Typing & Many Forms.
Interview Use
Prepare one clear explanation, one practical example, and one common mistake for this JavaScript Master Course topic.
Search Terms
javascript-complete-guide, javascript master course, javascript, complete, guide, oop, polymorphism, polymorphism in javascript – method overriding, duck typing & many forms
Related JavaScript Master Course Topics