Software Design Patterns in JavaScript
Glossary
127 terms from Software Design Patterns in JavaScript, in plain words, each with the chapter that teaches it.
A
- Abstract class
- A base class written only to be inherited from, never used directly. Its methods typically throw a "not implemented" error until a child class such as `PlainReport` fills them in.
- Abstract factory
- An object with several make methods that builds a family of parts that belong together, such as a carrier and a label printer for one shipping company.
- Adapter
- A small wrapper class that holds a library object you can't edit and offers the interface your code expects. UpsCarrier adapts UPS's cents-based API to a quote(items) method that returns dollars.
- Anti-pattern
- A common answer to a design problem that looks reasonable but causes more trouble than it solves. Naming them, such as god object, lets a team talk about them quickly.
- Architecture patterns (MVC, hexagonal architecture, CQRS, microservices)
- Larger-scale patterns that apply the same design ideas, such as separating responsibilities and loose coupling, to whole systems rather than single classes. Examples are MVC, hexagonal architecture, CQRS and microservices.
- Arrow function
- A short way to write an unnamed function, such as `(x) => Math.round(x * 100) / 100`. It is handy for tiny helpers, clocks and callbacks.
- assert (node:assert/strict)
- Node's built-in checking functions for tests. assert.equal compares two values, assert.deepEqual compares arrays and objects by content, and assert.throws checks that a function fails with a matching message. A failed assert throws and fails the test.
B
- beforeEach
- A function from node:test that runs your setup code before every test. At Kettle & Crane it builds a fresh repo, bus and clock so no test sees another test's orders.
- Behavioral pattern
- A pattern about how objects share work and decisions, such as Strategy and Observer.
- Builder
- A creational pattern where an object collects parts one chained call at a time and then makes the finished result in build(), checking it is complete. OrderBuilder refuses to build an order with no items.
C
- Cache
- Saved answers kept so the real work isn't repeated. A caching proxy around a carrier asks UPS only once per number of lines.
- Callback
- A function you hand to another function so it can call it later. The compare function passed to toSorted is a callback and a strategy.
- Chain of responsibility
- A pattern where a request passes along a line of handlers, each of which deals with it (for example rejects the order) or passes it on. Order checks like hasItems and knownCarrier form such a chain.
- Characterization test
- A test that records what existing code does today, right or wrong, so a redesign can't change it by accident. For Kettle & Crane's order code, the totals 467.5, 42.6 and 31.25 become the expected values.
- Class explosion
- A new class for every mix of choices, so the number of classes multiplies: two yes/no choices need 4 classes and three need 8.
- Class field
- A line in a class body, such as name = "ups", that sets a property on every new instance.
- Closure
- A function that remembers the variables from where it was created. percentOff(10) returns a discount function that still remembers pct is 10.
- Cohesion
- How well the things inside one piece of code belong together. A function that only works out shipping has high cohesion, which is good.
- Command
- A pattern that turns an action into an object with run and undo methods, so actions can be stored, replayed or reversed. AddItem lets the cart page offer Undo.
- Composite
- A pattern where a single item and a group answer the same method, so groups can contain other groups. A Bundle's price() asks each part, whether Item or Bundle, and adds the answers.
- Composition
- Building an object from smaller part objects that each do one job, a "has-a" relationship. A Product has a pricing part and a wrapping part.
- Composition root
- The one place, usually main.js, that builds the real parts and hands them to the code that needs them.
- Constructor injection
- Passing an object its dependencies as constructor arguments, to keep for its whole life. OrderLog receives its repo, clock and notifier this way.
- Copy-paste programming
- An anti-pattern of repeating the same code in many places, so every fix must be made many times and one place is missed.
- Coupling
- How much one piece of code depends on the details of another. Low coupling is good, because changing one part is less likely to break the other.
- Creational pattern
- A pattern about how objects get made, moving the "which class, with which settings?" decision into one place.
- CSV
- A plain-text table format with one row per line and values separated by commas, such as KC-1001,467.50. Jo wants the order report in this format.
D
- Decorator
- A wrapper with the same interface as the object it wraps that adds a little behavior and passes the call on. LoggedCarrier logs each quote, and decorators can be stacked.
- Default parameter value
- A value a parameter takes when the caller leaves it out, written like pricing = retail or qty = 1. It keeps the common case short.
- Delegation
- Handing a job to another object you hold instead of doing it yourself. Product.total asks its pricing and wrapping parts and adds their answers.
- Dependency
- Anything a piece of code needs to do its job, such as a database, a notifier or the clock.
- Dependency injection
- Giving code its dependencies from outside instead of letting it create or find them. That lets a test pass in fakes instead of touching disk, email or the real clock.
- Dependency inversion principle (DIP)
- The D of SOLID: high-level code such as order rules and low-level details such as printing should both depend on an interface, and you pass the detail in. confirmOrder depends on a Notifier, not on ConsoleNotifier.
- Design pattern
- A named, reusable solution to a common design problem. It is a shape for your code, not a library or code to copy.
- DI container
- A library that builds objects and their dependencies automatically from a list of rules. JavaScript programs rarely need one because plain calls in a composition root stay readable.
- Duck typing
- Using any object that has the methods you need, whatever its class. applyDiscount works with any rule that has applies and apply.
E
- Easy to change
- The goal of design: each business change touches one small, obvious place and breaks nothing else.
- ES module
- A JavaScript file that uses export and import to share code. A module runs only once however many files import it, which is why it works as a singleton.
- Event bus
- A small object where code registers listeners with `on` and announces events with `emit`, so the sender doesn't know who is listening. It is a simple form of the Observer pattern.
- EventEmitter
- Node's built-in class for publishing and listening to events with `on` and `emit`, much like a hand-written event bus. The browser's `addEventListener` follows the same idea.
- Express (and Fastify, Koa, Next.js)
- Express is the most used web framework for Node: you register routes and middleware with app.get and app.use, and it calls them when requests arrive. Fastify, Koa and Next.js use the same ideas of inversion of control, injection and middleware.
F
- Facade
- One simple function or class in front of several parts, so callers make one call and only the facade knows the steps. checkout prices, quotes and saves behind a single call.
- Factory
- A function or class whose job is making objects, so callers don't need to know which class to build.
- Factory method
- A Gang of Four pattern where a parent class has a method that makes a part and each child class overrides it to choose which object to make.
- Fake
- A simple working stand-in for a real part in tests, such as MemoryRepo or a notifier that stores messages in an array.
- Fixture
- The setup a test starts from, built fresh in beforeEach so every test begins in the same state.
- Fragile base class
- A parent class that its children depend on so closely that changing it quietly breaks them, such as adding tax to Product.total and also taxing wholesale products.
- Framework
- Code that runs your program and calls your code at the right moments, such as Node's test runner or Express.
G
- Gang of Four
- The nickname of the four authors of the 1994 book Design Patterns, which named 23 patterns in creational, structural and behavioral families.
- Generator
- A function written with function* that uses yield to hand back one item at a time, pausing until the loop asks for the next. It is an easy way to write your own iterator.
- Global mutable state
- Data at module level that any code can change, like the old orders array or a shared settings object. Tests then affect each other and depend on run order.
- God object
- An anti-pattern where one class or module does far too much, like a Shop class with 40 methods. The old placeOrder is a small god function.
- Golden hammer
- An anti-pattern of using one favorite tool, such as a class hierarchy or a factory, for every problem.
H
- Handler
- One link in a chain of responsibility: it deals with a request or passes it on. Express route functions are also called handlers.
- Has-a / is-a
- Two ways to relate objects. Composition says a product has a pricing rule, while inheritance says a promo card is a gift card.
- Hook
- The step a template method leaves for the caller or a subclass to supply, such as formatRow in the order report.
I
- Inheritance
- A child class reusing and extending its parent's code with `extends`, an "is-a" relationship. Deep inheritance trees tend to become hard to change.
- Injected clock
- A function passed in that returns the current time as a Date, such as () => new Date(). A test can pass one that always returns the same time.
- Instance
- An object made from a class with new. Each instance gets its own copy of the class's fields.
- Interface
- The set of methods that code expects an object to have, whatever its class. JavaScript has no `interface` keyword, so an interface is usually written down as a comment.
- Interface segregation principle (ISP)
- The I of SOLID: code shouldn't depend on methods it doesn't use, so keep interfaces small. A carrier only needs quote, not track and refund.
- Inversion of control
- A framework calling your code instead of your code calling it, summed up as "don't call us, we'll call you". The test runner calling your tests is an example.
- Iterator
- A pattern that steps through a collection one item at a time without showing how it is stored. Every for...of loop uses one.
J
- JSON
- A text format for storing data. JSON.stringify turns an array or object into JSON text, and JSON.parse reads it back.
K
- KISS
- "Keep it simple": of two designs that both work, choose the one that's easier to read.
L
- Library
- A set of tools your code calls when it wants to, so your code stays in charge. This contrasts with a framework.
- Liskov substitution principle (LSP)
- The L of SOLID: a child class must work anywhere its parent works. LockedCard breaks it because its topUp throws, so a loop over gift cards fails.
- Listener
- A function that is called when an event it subscribed to is emitted, such as sendEmail on "orderPlaced".
- Lookup table
- An object or Map from names to values, classes or functions, used instead of an if chain. CARRIERS and TRANSITIONS are lookup tables.
M
- Magic number
- A number in code with no name to say what it means, like 75 and 0.85 in the old placeOrder. The fix is a named constant such as FREE_SHIPPING_AT.
- Map
- A built-in JavaScript collection from keys to values, with `get`, `set` and `has`. It is safer than a plain object for lookups by user-typed names, because a name like `"constructor"` can't match something inherited.
- Method chaining
- Calling methods one after another, each returning this so the next call can follow straight on.
- Middleware
- Handlers every web request passes through, such as logging or login checks, each able to pass the request on with next() or stop it. It is chain of responsibility in web frameworks.
- Mock
- A test stand-in that also records how it was called so the test can check it. Node's node:test module can create them with mock.fn().
N
- new.target
- Inside a constructor, the class that new was called on. The parent Report uses it to refuse being built directly.
- node --test
- The terminal command that runs Node's built-in test runner, finding every *.test.js file in the folder. The plain node file.js form runs a script.
- Node.js
- A program that runs JavaScript outside a browser. Modern versions (22 or newer here) include a built-in test runner and file tools, so many programs need no extra packages.
- node:test
- Node's built-in test framework, imported as node:test, with test, beforeEach and mock. It calls your test functions for you, so it is an example of inversion of control.
- npm
- Node's package manager, used to install libraries and plugins such as Express. Programs that use only what Node includes need no packages from it.
- Nullish coalescing (??)
- An operator that uses its right side only when the left is undefined or null. discountFor uses it to fall back to noDiscount when a code isn't found.
O
- Object.freeze
- Makes an object read-only. Because modules run in strict mode, assigning to a frozen object throws a TypeError.
- Object.hasOwn
- Checks whether a key is the object's own, not inherited, so a name like "constructor" can't sneak into the CARRIERS lookup.
- Observer
- A pattern where the code where something happens (the subject) keeps a list of listeners and calls each one when the event happens, without knowing what they do.
- Open/closed principle (OCP)
- The O of SOLID: code should be open for extension but closed for modification, so you add behavior with new code instead of editing code that works. A new discount is a new class added to RULES.
- Optional chaining (?.)
- Calls a method or reads a property only if the value isn't undefined or null, otherwise it does nothing. history.pop()?.undo() safely does nothing when the stack is empty.
- Other patterns (not covered)
- Less common Gang of Four patterns: Flyweight (share objects to save memory), Bridge (let a concept and its implementation vary separately), Mediator (one object manages how others talk), Memento (save state to restore later), Visitor (add operations without editing classes) and Interpreter (a small language as classes).
- Over-engineering
- Building more structure than the problem needs, such as an abstract class, factory and registry for a single discount.
- Override
- Writing a method in a child class with the same name as the parent's, so the child's version runs instead. In a factory method each child overrides the make method.
P
- padStart
- A string method that pads the text on the left to a given width, so padStart(8) right-aligns numbers in report columns.
- Plugin
- Code a framework finds and runs to add a feature with no change to the framework itself, such as Express plugins installed with npm.
- Premature abstraction
- Adding an interface, base class or factory before you have two or three real cases, which guesses what will vary and is harder to undo than plain code.
- Private field (#)
- A class field whose name starts with #, which only that class's own methods can touch. JavaScript enforces it.
- Prototype
- A creational pattern that makes new objects by copying a ready-made one and changing a little, using spread or structuredClone. Bloom Café's holiday order copies its weekly order.
- Proxy
- A same-interface wrapper that controls access to the real object, for example by creating it only when needed, checking permissions or caching answers.
- Publish/subscribe
- Observer described in publishing terms: the subject publishes events and listeners subscribe to them.
R
- reduce
- An array method that combines all items into one value using a function you supply, such as summing price times qty for an order.
- Refactoring
- Restructuring existing code in small steps without changing what it does, usually with tests pinning the old behavior. For example, Kettle & Crane's tangled order module is split into small parts that give the same totals.
- Registry
- A table from names to classes or functions that code looks up when needed, such as CARRIERS or Express's route table.
- Repository
- An object that stores and finds things for the rest of the code, so nothing else knows how they're stored. MemoryRepo has nextId, save and all.
- Rule of three
- Write the code the first time, notice the repeat the second time, and extract the shared part the third time, when you know what really varies.
S
- Service locator
- A global registry that code reaches into for its dependencies. It looks tidy but hides dependencies and makes tests change the global, unlike injection.
- Simple factory
- One function that knows every class and picks one from a name, usually through a lookup table. createCarrier("ups") returns a UpsCarrier.
- Single responsibility principle (SRP)
- The S of SOLID: a piece of code should have one reason to change. Pricing and saving labels change for different reasons, so they belong in separate functions.
- Singleton
- A class that allows only one instance and hands everyone that same instance. In JavaScript an ES module already behaves this way, so its exported values are shared.
- SOLID
- Five design principles named by their first letters: single responsibility, open/closed, Liskov substitution, interface segregation and dependency inversion.
- Spaghetti code
- Code so tangled with ifs, globals and jumps that you can't follow one path through it.
- splice
- An array method that removes (and can insert) items at a given position. Paired with `indexOf`, it removes one specific item, as in undoing an added cart item or removing a listener.
- Spread syntax
- The ... syntax that copies an object's or array's fields into a new one. { ...weekly, qty: 20 } copies the order and overrides qty, leaving the original alone.
- SQLite
- A small file-based database. A `SqliteRepo` with the same methods as `MemoryRepo` shows that storage can change without touching `OrderLog`.
- State machine
- Something that is always in exactly one of a fixed set of states, with rules for which moves between them are allowed. An order's moves are listed in the TRANSITIONS table.
- Strategy
- One interchangeable way of doing a job, where all versions share the same shape so the caller doesn't care which it gets. In JavaScript it is usually a function, such as a discount.
- Strict mode
- A stricter JavaScript mode that ES modules always use. In it, assigning to a frozen object throws an error instead of failing silently.
- Structural pattern
- A pattern about how objects fit together: connecting pieces not made for each other or wrapping one object in another.
- structuredClone
- A built-in function that makes a full copy of nested data, used to copy a prototype template.
- Stub
- A test stand-in that just returns fixed answers, such as a clock that always says 4:00 p.m.
- Subject
- In the Observer pattern, the object or code where an event happens and whose listeners subscribe to it. An event bus is a subject.
T
- Template literal
- A string in backticks with ${...} slots that are filled with values, such as `KC-${1001 + n}`.
- Template method
- A pattern that fixes a job's steps in one place and leaves one step, the hook, for the caller to supply as a function or in a child class. makeReport fixes the report layout while formatRow varies.
- toFixed
- A number method that shows a number with a set number of decimals as text, so 467.5.toFixed(2) is "467.50".
- toISOString
- A Date method that turns a time into standard text such as "2026-10-23T16:00:00.000Z". It is how orders get their placed timestamp.
- toSorted
- An array method that returns a new sorted array using a compare function you pass in. The compare function is a strategy.
- Transition
- A move from one state to another, such as paid to shipped. Allowed transitions are listed per state in a table.
- Tree
- A structure of items that contain smaller items, like bundles inside bundles, down to single items.
- TypeScript
- A separate language that adds types to JavaScript. It can check an interface before the code runs and adds an abstract keyword.
U
- Undo stack
- A list of commands already run, newest on top. Undo pops the last one and reverses it.
W
- Wrapper
- An object that holds another object and stands in front of it. Adapters, decorators and proxies are all kinds of wrapper.
Y
- YAGNI
- "You aren't gonna need it": don't build for a future need until it is real, because most guessed needs never arrive or come in a different shape.