Full answer
Inheritance: class Dog extends Animal gives Dog all behavior of Animal and lets it override parts. It works well when there is a stable, honest subtype relationship and the base class is designed to be extended. Its costs:
- Tight coupling: a subclass depends on the internal details of the base class, so a change in the base can break subclasses (the fragile base class problem). A classic example is a subclass of a collection that overrides
addandaddAll, whereaddAllin the base callsadd, so items get counted twice. - Rigidity: the hierarchy is fixed at design time. If a
Robotand aDuckboth needfly, but only some robots swim and some ducks do not, a tree of classes cannot express every combination. You end up with duplicated code or a big base class. - The gorilla and banana problem: you wanted a banana, but you got a gorilla holding the banana and the whole jungle, meaning inherited methods and state you do not want.
- Hard testing: a subclass cannot be tested without its ancestors.
Composition: build an object from small, focused parts and delegate to them. A Robot has a mover, a speaker, and a battery. Behaviors are plain functions or small objects that can be swapped, tested alone, and combined freely. In JavaScript this is natural: factory functions that return objects, object spread to combine capabilities, dependency injection through constructor arguments, and functions as strategy values.
Rules of thumb:
- Ask "is X a kind of Y in all cases?" If not, do not inherit.
- Prefer a shallow hierarchy, ideally one or two levels.
- Inherit from abstractions designed for it (such as
Error,EventTarget, and framework base classes), and compose everything else. - Share small pieces of behavior with functions, mixins, or helper objects.
Inheritance is not wrong. The point is to choose it for subtype relationships, and use composition for sharing behavior. Frameworks have moved in this direction: React uses composition of components and hooks instead of class inheritance for sharing logic.
// 1. The fragile base class problem
class CountingList {
items = [];
add(item) {
this.items.push(item);
}
addAll(list) {
for (const item of list) this.add(item);
}
}
class CountingListWithTotal extends CountingList {
total = 0;
add(item) {
this.total++;
super.add(item);
}
addAll(list) {
this.total += list.length;
super.addAll(list); // the base class calls this.add for each item, so every item is counted twice
}
}
const inherited = new CountingListWithTotal();
inherited.addAll(['a', 'b', 'c']);
console.log('inheritance: items', inherited.items.length, 'total', inherited.total);
// 2. The same feature with composition: wrap a list and delegate to it
class CountedList {
#list = new CountingList();
total = 0;
add(item) {
this.total++;
this.#list.add(item);
}
addAll(list) {
for (const item of list) this.add(item);
}
get items() {
return [...this.#list.items];
}
}
const composed = new CountedList();
composed.addAll(['a', 'b', 'c']);
console.log('composition: items', composed.items.length, 'total', composed.total);
// 3. Combining capabilities freely with factory functions
const canWalk = (state) => ({ walk: () => `${state.name} walks` });
const canSwim = (state) => ({ swim: () => `${state.name} swims` });
const canFly = (state) => ({ fly: () => `${state.name} flies` });
const canSpeak = (state, sound) => ({ speak: () => `${state.name} says ${sound}` });
function createDuck(name) {
const state = { name };
return { ...canWalk(state), ...canSwim(state), ...canFly(state), ...canSpeak(state, 'quack') };
}
function createRobot(name) {
const state = { name };
return { ...canWalk(state), ...canFly(state), ...canSpeak(state, 'beep') };
}
function createPenguin(name) {
const state = { name };
return { ...canWalk(state), ...canSwim(state), ...canSpeak(state, 'honk') };
}
const all = [createDuck('Duck'), createRobot('Robot'), createPenguin('Penguin')];
console.log(all.map((x) => Object.keys(x).join('/')));
console.log(all.map((x) => x.speak()), all[2].fly === undefined);
// 4. Dependency injection: behavior supplied from outside, easy to replace in tests
class Notifier {
constructor(send) {
this.send = send;
}
notify(user) {
return this.send(`Hello ${user}`);
}
}
const sent = [];
console.log(new Notifier((message) => sent.push(message)).notify('Asha'), sent);Run with Node.js v24.22.1 as js-136.js; two runs gave identical output. Output: inheritance: items 3 total 6 composition: items 3 total 3 [ 'walk/swim/fly/speak', 'walk/fly/speak', 'walk/swim/speak' ] [ 'Duck says quack', 'Robot says beep', 'Penguin says honk' ] true 1 [ 'Hello Asha' ]
Key points
- Inheritance is "is a"; composition is "has a" with delegation.
- Deep inheritance causes tight coupling, fragile base classes, and rigid combinations.
- Composition lets you swap, test, and combine small parts, using factories, spread, and injection.
- Use inheritance for true subtypes and for classes designed to be extended, such as Error.
- Keep hierarchies shallow and share behavior with functions or helper objects.
Common mistakes
- Inheriting just to reuse a few methods when the relationship is not "is a".
- Overriding a method that the base class calls internally.
- Building hierarchies three or more levels deep.
- Treating composition as a rule that bans inheritance.
Follow-ups
- How do mixins relate to composition and inheritance?
- Why do frameworks such as React prefer composition?
- How would you decide whether Error subclasses are a good use of inheritance?
Tips
- Give the double counting example; it is memorable and concrete.
- Say when inheritance is still right.
- Mention factory functions and dependency injection as the JavaScript tools for composition.