What Composition Means
You'll learn: How composition assembles complex objects from small, independent pieces rather than building rigid inheritance chains.
The Core Idea
Composition means creating functionality by combining simple, focused objects or functions together, rather than forcing objects to inherit behavior from parent classes. Think of it like building with LEGO blocks: you snap together small, single-purpose pieces to create something complex, rather than carving one large block into the shape you need.
In JavaScript, composition typically means giving an object certain capabilities by mixing in behaviors from other sources, or chaining simple functions together to achieve complex results.
Composition vs Inheritance
Inheritance says "A dog is-a animal." Composition says "A dog has the ability to walk, bark, and eat." The difference is subtle but powerful:
- Inheritance: Rigid hierarchies where subclasses depend on parent classes
- Composition: Flexible assembly where objects get exactly the capabilities they need
Why It Matters
Composition solves the problems you learned about in "Why Inheritance Can Be Problematic." Instead of fragile parent-child relationships, you build objects from independent, reusable parts. If you need to change one capability, you modify just that piece without breaking an entire class tree.
Imagine building a video game character. With inheritance, you might struggle with "Does FlyingFish extend Fish or FlyingThing?" With composition, you simply give it swimming behavior AND flying behavior—no awkward hierarchy required.
Key Takeaway: Composition builds objects by combining small, focused behaviors rather than inheriting from monolithic parent classes, leading to more flexible and maintainable code.