JavaScript Design Patterns Interview Questions and Answers
Review reusable design principles and patterns, including when they help and when they add needless complexity.
Frequently Asked Questions
Important questions are highlighted in the sections below; select one to jump to its answer.
- What is the DRY Principle?
- What is a Singleton, and what is one trade-off?
- What problem does the Factory pattern solve?
- How does the Module pattern encapsulate state?
- Build a small notification factory
- What does a Command object need to support undo?
- Why can module scope act like a Singleton in JavaScript?
Theoretical JavaScript Interview Questions
Separation of concerns means keeping different responsibilities in different places - HTML structures content, CSS handles presentation, and JavaScript handles behavior. In component-based frameworks it means not mixing data-fetching logic with rendering logic. It makes code easier to maintain and test because each piece only needs to know about its own job.
DRY - Don't Repeat Yourself - means every piece of logic should live in one place. When you copy-paste code, you create multiple places to update when requirements change, and they inevitably drift out of sync. Extract shared logic into functions, modules, or components. That said, don't over-DRY prematurely - sometimes two similar-looking pieces of code have genuinely different concerns, and forcing them together creates more coupling than it's worth.
Design patterns are named, reusable solutions to common software problems - they're vocabulary for communicating architectural decisions. In JavaScript you'll encounter the Module pattern (encapsulating code with closures), Observer/Pub-Sub (event-driven communication), Factory (creating objects without exposing constructor logic), and Singleton (ensuring one instance). Knowing the names helps you recognize and discuss architectural choices clearly.
A Factory centralizes object creation behind a function or method, so callers request an object without depending on its construction details. It is useful when creation logic varies or should be kept separate from use.
A Singleton exposes one shared instance of a value. It can simplify access to truly shared state, but hidden global state and tight coupling can make code harder to test.
A module keeps implementation details in a private scope and exposes only selected functions or values. ES modules provide file-level scope and explicit exports for this purpose.
Observers subscribe to a subject and are notified when its state or events change; they should also be able to unsubscribe. This separates the publisher from the concrete listeners, but careless subscriptions can retain objects or cause duplicate notifications.
Dependency injection supplies collaborators from outside a component instead of having the component construct them internally. Tests can pass controlled fakes, while production code supplies real implementations.
Strategy selects interchangeable algorithms, usually chosen by the caller or configuration. State represents an object's current condition and commonly changes which behavior is available as transitions occur.
A decorator wraps an object or function, forwards its existing interface, and adds behavior before or after delegation. Wrappers can be composed, but should preserve expected return values, errors, and `this` behavior.
A command encapsulates an operation and the data needed to execute it; undo requires enough prior state or a compensating operation to reverse its effects. Commands are often recorded in a history stack, with care for irreversible side effects.
Within a module instance, top-level state is shared by importers of that same resolved module, so an exported object can behave like a shared instance. Separate realms, workers, duplicated module copies, or separate module URLs can produce distinct instances.
Return an unsubscribe function from registration and call it when the observer's lifetime ends. Clear one-shot listeners after delivery where appropriate, and avoid retaining observers in long-lived publishers after they are no longer needed.
Choose a pattern when it makes a recurring design constraint clearer or reduces coupling, and keep the solution proportional to the problem. A pattern that adds indirection without a concrete benefit increases maintenance cost.
JavaScript Practical and Coding Interview Questions
Problem: Write a factory function that accepts a message and severity and returns a notification object. Use defaults for missing values, then create and print an error notification.
function createNotification(message, severity = "info") {
return { message, severity };
}
const notice = createNotification("Save failed", "error");
console.log(notice);