Advanced Design Patterns in JavaScript
Published by Brayan K
Design patterns are proven, reusable solutions to common software problems — like the Singleton, Observer, and Factory patterns — that give developers a shared vocabulary for structuring flexible, maintainable JavaScript code.
Part of the free JavaScript course at LearnCodingFast — hands-on lessons with examples you run in your browser, plus practice exercises and a quick quiz.
A pattern earns its place by isolating a specific change
Suppose a notification gains an email channel. The changing part is delivery, not every caller. Give delivery a small behavioral contract, then choose it at a composition boundary. A factory controls creation; a strategy supplies replaceable behavior. Neither requires a class hierarchy.
function createNotifier(send) {
// Validate configuration before a caller tries to use the notifier.
if (typeof send !== "function") throw new TypeError("send must be a function");
return name => send("Hello, " + name);
}
const recorded = [];
// These are deterministic local strategies, not network services.
const inbox = createNotifier(text => { recorded.push(text); return "stored"; });
const preview = createNotifier(text => text.toUpperCase());
console.log(inbox("Mia"), preview("Mia"));
console.log(recorded.join("|"));
// ✅ Expected output:
// stored HELLO, MIA
// Hello, MiaThe contract includes what send receives, what it returns and how it fails. A shared method name alone cannot promise substitutability. Design Patterns owns basic pattern selection and undo history; this lesson examines scope, adapters and composition contracts.
function createNotifier(send) {
if (typeof send !== "function") throw new TypeError("send must be a function");
return text => send(text);
}
createNotifier("email");
// ✅ Expected error:
// TypeError: send must be a functionFactories give state a lifetime; global singletons hide that decision
function createCounter() {
let count = 0;
return { next: () => ++count };
}
const first = createCounter(), second = createCounter();
console.log(first.next(), first.next(), second.next());
// ✅ Expected output:
// 1 2 1A factory can create one service per application, request, account or test. Pick that lifetime deliberately. A module-level object can be shared within the module graph, but it is not one universal instance across tabs, workers, separate builds or server processes. JavaScript Modules: ES6 Imports, Exports, Bundling owns module caching and separate module instances.
const shared = { prefix: "A" };
const first = () => shared.prefix;
const second = value => { shared.prefix = value; };
console.log(first());
second("B");
console.log(first());
// ✅ Expected output:
// A
// BThis sharing may be intentional, but reset order and concurrent callers now matter. Prefer an injected instance when independent lifetimes are useful. “Singleton” names a creation/access constraint; it does not make mutable state safe or automatically isolate users.
Adapters translate meaning, not just method names
An existing dependency may accept different units or produce a different shape. Keep that translation in one adapter and state its rounding and validation rules. An adapter that merely renames a method while dropping units silently violates its contract.
function secondsAdapter(scheduleMilliseconds) {
return seconds => {
if (!Number.isSafeInteger(seconds) || seconds < 0 ||
!Number.isSafeInteger(seconds * 1000))
throw new RangeError("seconds must convert to safe milliseconds");
return scheduleMilliseconds(seconds * 1000);
};
}
const delays = [];
const schedule = secondsAdapter(ms => { delays.push(ms); return delays.length; });
console.log(schedule(3), schedule(0));
console.log(delays.join(","));
// ✅ Expected output:
// 1 2
// 3000,0No timer runs here: the recorded boundary checks the units, including zero. The adapter does not promise that a timer fires at an exact deadline. Debouncing & Throttling for Performance owns scheduling and cancellation mechanics.
function traced(fn, trace) {
return function (...args) {
trace.push("call");
return Reflect.apply(fn, this, args);
};
}
const events = [];
const object = { factor: 3, scale: traced(function (n) { return this.factor * n; }, events) };
console.log(object.scale(4), events.join(","));
// ✅ Expected output:
// 12 callA decorator adds behavior around an existing contract. Forgetting return changes the result; an arrow wrapper can lose a dynamic receiver. Higher-Order Functions & Currying owns call forwarding. Here the design question is whether the added behavior changes a guarantee callers rely on.
Wrapper order and async wrappers are observable choices
const brackets = fn => value => "[" + fn(value) + "]";
const upper = fn => value => fn(value.toUpperCase());
const label = value => "hello " + value;
console.log(brackets(upper(label))("Mia"));
const upperResult = fn => value => fn(value).toUpperCase();
console.log(upperResult(brackets(label))("Mia"));
// ✅ Expected output:
// [hello MIA]
// [HELLO MIA]Write down whether a wrapper transforms input, output or both. Logging before a call and logging after settlement are different behaviors. A wrapper that catches an error and returns a default also changes the failure contract.
const pending = Promise.resolve("done");
const task = () => pending;
const direct = (...args) => task(...args);
const wrapped = async (...args) => task(...args);
console.log(direct() === pending, wrapped() === pending);
console.log(await wrapped());
// ✅ Expected output:
// true false
// doneconst original = new Error("delivery");
const loggerFailure = new Error("logger");
function unsafeWrapper(fn) {
try { return fn(); }
catch (error) { throw loggerFailure; }
}
try { unsafeWrapper(() => { throw original; }); }
catch (error) { console.log(error === original, error === loggerFailure); }
// ✅ Expected output:
// false trueChoose the reporting policy explicitly: report without masking the original error, or return a documented combined outcome. Error Handling Patterns in Large JS Apps owns those recovery choices. A pattern name is not evidence that a wrapper preserves them.
A facade simplifies a workflow without creating a transaction
const records = [];
async function publish({ save, announce }, text) {
const id = await save(text);
await announce(id);
return id;
}
try {
await publish({
save: async text => { records.push(text); return records.length; },
announce: async () => { throw new Error("announcement failed"); }
}, "draft");
} catch (error) { console.log(error.message, records.length); }
// ✅ Expected output:
// announcement failed 1The facade hides call sequencing, not the partial effect. Transaction support, idempotency, compensation and retry policy need their own contracts. Automatically repeating this entire facade could save the draft twice. The example uses local arrays to make that boundary visible.
Observer-style notification has separate rules for listener identity, reentrancy, removal and failures. Custom Event Emitters & Observer Pattern owns those rules; a facade should not silently invent different ones. Avoid adding an observer or registry when one explicit callback already expresses the needed variation.
Guided exercise: keep the adapter boundary in one place
Complete the literal hints. The policy receives a fresh selected object; the adapter translates its output to the external dependency’s string input.
const calls = [];
const send = text => { calls.push(text); return 7; };
function notify(message) {
const selected = { name: message.___ }; // 👉 replace ___ with name
const text = "Hello, " + selected.name;
___ send(text); // 👉 replace ___ with return
}
console.log(notify({ name: "Mia", secret: "omit" }));
console.log(calls.___("|")); // 👉 replace ___ with join
// ✅ Expected output:
// 7
// Hello, MiaIndependent brief: a scoped message router
Implement createMessageRouter(entries, format). Validate a dense array of entries with nonblank string keys and callable send functions; trim registration keys and reject duplicates before exposing a router. Snapshot those selected functions so later entry edits do not replace them. The returned frozen object has dispatch(key, message).
Dispatch uses an exact registered key. Validate name and text strings, pass only those fields in a fresh frozen object to the synchronous formatter, and require a string result before sending. Return the selected handler’s exact value or promise and propagate its original failures. Unknown channels and invalid inputs must not call format or send. No retries, network, persistence, authorization or global registry are part of this contract.
function createMessageRouter(entries, format) {
if (!Array.isArray(entries) || typeof format !== "function")
throw new TypeError("entries and format are required");
const handlers = new Map();
for (let i = 0; i < entries.length; i++) {
const entry = entries[i];
if (!Object.hasOwn(entries, i) || entry === null || typeof entry !== "object" ||
typeof entry.key !== "string" || entry.key.trim() === "" ||
typeof entry.send !== "function")
throw new TypeError("each entry needs a key and send function");
const key = entry.key.trim();
if (handlers.has(key)) throw new RangeError("duplicate channel");
handlers.set(key, entry.send);
}
return Object.freeze({
dispatch(key, message) {
if (typeof key !== "string" || !handlers.has(key))
throw new RangeError("unknown channel");
if (message === null || typeof message !== "object" ||
typeof message.name !== "string" || typeof message.text !== "string")
throw new TypeError("message needs name and text strings");
// Select approved fields before handing data to the formatting policy.
const input = Object.freeze({ name: message.name, text: message.text });
const text = format(input);
if (typeof text !== "string") throw new TypeError("format must return text");
const send = handlers.get(key);
// Do not wrap this result: callers retain its exact value or promise.
return send(text);
}
});
}
const seen = [], pending = Promise.resolve("queued");
const entries = [{ key: " inbox ", send: text => { seen.push(text); return pending; } }];
const router = createMessageRouter(entries, data => data.name + ": " + data.text);
entries[0].send = () => "changed";
const message = { name: "Mia", text: "Hello", secret: "omit" };
console.log(router.dispatch("inbox", message) === pending);
console.log(seen.join("|"), message.secret);
for (const key of ["missing", " inbox "]) {
try { router.dispatch(key, message); }
catch (error) { console.log(error.name, error.message); }
}
try { createMessageRouter([{ key: "A", send() {} }, { key: " A ", send() {} }], String); }
catch (error) { console.log(error.name, error.message); }
const bad = createMessageRouter([{ key: "x", send() { throw new Error("must not send"); } }], () => 42);
try { bad.dispatch("x", message); }
catch (error) { console.log(error.name, error.message); }
console.log(Object.isFrozen(router), seen.length);
// ✅ Expected output:
// true
// Mia: Hello omit
// RangeError unknown channel
// RangeError unknown channel
// RangeError duplicate channel
// TypeError format must return text
// true 1
Practice quiz
What does this complete program print? function make(){let n=0;return()=>++n}const a=make(),b=make();console.log(a(),a(),b());
- 1 2 1
- 1 2 3
- 1 1 1
- 0 1 0
Answer: 1 2 1. Each factory call owns a separate closure.
What does this complete program print? const state={value:1};const read=()=>state.value;state.value=2;console.log(read());
- 1
- 2
- undefined
- ReferenceError
Answer: 2. Shared mutable state remains visible through the closure.
What does this complete program print? const adapt=fn=>seconds=>fn(seconds*1000);console.log(adapt(ms=>ms)(2));
- 2
- 0.002
- 2000
- undefined
Answer: 2000. The adapter converts units at the dependency boundary.
What does this complete program print? const object={n:4,run:function(x){return this.n+x}};function forward(fn){return function(...args){return Reflect.apply(fn,this,args)}}object.run=forward(object.run);console.log(object.run(3));
- 3
- 4
- undefined
- 7
Answer: 7. Reflect.apply preserves the invocation receiver.
What does this complete program print? const original=Promise.resolve(1);const direct=()=>original;const wrapped=async()=>original;console.log(direct()===original,wrapped()===original);
- true false
- true true
- false true
- false false
Answer: true false. An async function returns its own adopting promise.
What does this complete program print? const prefix=fn=>x=>"["+fn(x)+"]";const fn=x=>"a"+x;console.log(prefix(fn)("b"));
- a[b]
- [ab]
- [b]
- ab
Answer: [ab]. This wrapper transforms the result of the inner function.
What does this complete program print? const saved=[];async function work(){saved.push("A");throw Error("later")}try{await work()}catch{}console.log(saved.length);
- 0
- undefined
- 1
- 2
Answer: 1. Failure does not roll back the earlier array mutation.
What does this complete program print? const entry={send:()=>1};const saved=entry.send;entry.send=()=>2;console.log(saved(),entry.send());
- 2 2
- 1 1
- 2 1
- 1 2
Answer: 1 2. Capturing a function value is different from reading the mutable entry later.
Continue this course
- Previous: Working with Dates, Timezones & Intl API
- Next: Writing Maintainable & Scalable Code Architecture — Structure large codebases with clear boundaries, naming, and conventions
- Quick reference: JavaScript cheat sheet