CodeZettaInterview Hub

JavaScript · OOP · Mid-Level · Comparison

When would you choose composition over inheritance in a JavaScript codebase?

Short Interview Answer

Prefer composition when behavior is reusable across unrelated types or hierarchies would be deep/fragile; use inheritance for true 'is-a' with shared identity.

Detailed Explanation

Inheritance couples types: changes in a base class ripple downward (fragile base class). Composition (`has-a`) plugs small collaborators into a host object/function, easing testing and reuse. In JS, composition is natural via closures, dependency injection, and mixins — but mixins can conflict. Use inheritance for framework extension points (`extends Component`) or clear taxonomic relationships. A practical heuristic: if you only need a few methods, wrap or delegate; if you need polymorphism with shared interface and lifecycle, inheritance or explicit interfaces (TypeScript) may fit.

Example

function withLogger(service) {
  return {
    ...service,
    save(data) {
      console.log('save', data);
      return service.save(data);
    },
  };
}

Interview Tip

Give one concrete domain example (e.g. payment processors vs shared BaseManager god class).

Common Mistake

Dogmatically banning inheritance even for genuine framework subclassing.

Did you know this answer?