Course contentsShow
← JavaScript
Lesson 779 of 2,72318. ClassesFree lesson

When to Use Inheritance vs Composition

Recognizing when extends is appropriate versus preferring composition patterns.

When to Use Inheritance vs Composition

You'll learn: How to decide whether extends or composition patterns better fit your design needs.

The Core Question

Inheritance (using extends) models an "is-a" relationship: a Dog is a Animal. Composition models a "has-a" or "uses-a" relationship: a Car has an Engine. While JavaScript gives you powerful inheritance with classes, composition often leads to more flexible, maintainable code.

When Inheritance Makes Sense

Use extends when:

  • There's a clear, stable "is-a" relationship (Manager extends Employee)
  • You need to override specific behaviors while keeping most parent functionality
  • The inheritance hierarchy is shallow (avoid deep chains)
  • Subclasses genuinely share the parent's interface
class Animal {
  constructor(name) {
    this.name = name;
  }
  speak() {
    return `${this.name} makes a sound`;
  }
}

class Dog extends Animal {
  speak() {
    return `${this.name} barks`;
  }
}

When Composition Is Better

Prefer composition when:

  • Objects need behaviors from multiple sources (multiple inheritance isn't directly supported)
  • Relationships might change at runtime
  • You want loose coupling between components
const canSwim = {
  swim() {
    return `${this.name} is swimming`;
  }
};

const canFly = {
  fly() {
    return `${this.name} is flying`;
  }
};

class Duck {
  constructor(name) {
    this.name = name;
    Object.assign(this, canSwim, canFly);
  }
}

Here, Duck has swimming and flying abilities rather than inheriting from a complex hierarchy.

Key Takeaway: Use inheritance for clear "is-a" relationships with stable hierarchies; favor composition when you need flexibility, multiple behaviors, or want to avoid rigid class structures. When in doubt, start with composition—it's easier to refactor later.