Design Patterns
A design pattern is a proven answer to a recurring code-structure problem. In JavaScript they are implemented differently than in Java: instead of rigid interfaces you work with closures, first-class objects, and ES6 classes. So the same pattern often has two forms — a closure form and a class form.
In an interview, out of the whole GoF catalog three come up most: the factory function (and how it differs from new), the abstract factory (a creational pattern that decouples calling code from concrete constructors), and the decorator (a structural pattern that extends an object's behavior without editing its class). Their breakdown is in the layer below.
Topic map
- Classic patterns — factory, abstract factory, decorator — three GoF patterns in JavaScript, their mechanics, and the typical interview traps.
Common traps
| Mistake | Consequence |
|---|---|
Calling a factory function with new | An extra bound this; the factory already returns the object |
Thinking factory objects share a prototype like new-built ones | There is no automatic prototype link — they are different mechanisms |
Letting an abstract factory's base create return something | The abstract factory becomes callable directly — the point is lost |
Forgetting the default/else branch in a factory | An unknown type silently returns undefined instead of throwing |
| Editing the wrapped class instead of wrapping it in a decorator | The open/closed principle is broken |
Forgetting super.do(...) in a decorator | The inner object of the chain is never called |
Interview relevance
Patterns are asked as a maturity signal: do you understand the mechanics behind the name rather than just recall the name. A candidate who explains a factory as "a function returning an object with no this binding and private state in a closure" is stronger than one who says "a factory creates objects".
Typical checks:
- How a factory function differs from a
newconstructor (nothisbinding, no automatic prototype link, private closure state). - How an abstract factory decouples calling code from concrete products.
- How a decorator extends behavior without touching the original class, and why a shared interface enables composition.
Common wrong answer: "a decorator is just class inheritance". Inheritance fixes the extension in a single subclass; a decorator wraps the object at runtime, and decorators with a shared interface stack in any order and any number.