Design Patterns Junior cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

  1. 1. What is a design pattern?

    Correct answer: A typical solution to a recurring design problem

    A pattern isn't code but a description of an idea: what problem it solves, what parts the solution consists of, and its pros and cons. The implementation depends on the language and context. Knowing patterns gives a team a shared vocabulary: "we need a strategy here" is clear without long explanations.

  2. 2. Into which three groups are the classic GoF patterns divided?

    Correct answer: Creational, structural, behavioral

    Creational patterns deal with creating objects (Factory, Builder, Singleton), structural ones with composing objects (Adapter, Decorator, Facade), behavioral ones with interaction and distribution of responsibilities (Observer, Strategy, Command). The "Gang of Four" book (1994) described 23 patterns.

  3. 3. What does the Singleton pattern guarantee?

    Correct answer: A class has only one instance and a global access point to it

    Examples: one API client, one logger, one DB connection. In JS, the simplest singleton is a module: export const api = new ApiClient() - a module runs once, and all importers get the same object.

  4. 4. Why is Singleton often called an anti-pattern?

    Correct answer: It introduces hidden global state and makes testing harder

    Code that accesses a singleton directly depends on it implicitly: tests affect each other, and swapping the implementation is hard. A compromise is to create one instance but pass it explicitly (dependency injection) so tests can substitute a mock.

  5. 5. What problem does the Factory pattern solve?

    Correct answer: Creating objects without tying code to their concrete classes

    A createNotification(type) function returns an EmailNotification or a PushNotification, and the calling code works with a common interface. A new type is added in one place. In JS, a factory is often just a function that returns an object.

  6. 6. How does the Observer pattern work?

    Correct answer: An object keeps subscribers and notifies them when its state changes

    The subject provides subscribe/unsubscribe and calls callbacks on change. Web examples: addEventListener, store subscriptions in Redux and Zustand, RxJS. The key thing is to remember to unsubscribe, otherwise you get memory leaks.

  7. 7. How does Pub/Sub differ from the classic Observer?

    Correct answer: A broker connects publishers and subscribers

    In Observer, subscribers register directly with the subject. In Pub/Sub there's an intermediary (an event bus, a message broker), and participants know only channel names. This decouples parts of the system more strongly but makes the event flow harder to trace.

  8. 8. What is the Strategy pattern?

    Correct answer: A family of interchangeable algorithms chosen at runtime

    Instead of a long if/else by delivery type - a strategies object { courier: calcCourier, pickup: calcPickup }, and the code calls the right one. A JS example is the compare function in sort(compareFn): the sorting algorithm stays the same, while the comparison strategy is plugged in.

  9. 9. What does the Decorator pattern do?

    Correct answer: Adds behavior to an object or function by wrapping it

    The wrapper implements the same interface and adds logic before or after the call: caching, logging, retries. Examples: debounce(fn), withAuth(Component) (a HOC), @ decorators in TypeScript. Wrappers can be combined.

  10. 10. When do you need an Adapter?

    Correct answer: When a foreign interface must fit your code

    Example: the API returns { user_name, created_at }, while the UI expects { name, createdAt: Date }. An adapter function at the boundary transforms the data, and when the API changes only it needs editing. Third-party SDKs are adapted to your own interface the same way.

  11. 11. What is a Facade?

    Correct answer: A simple interface on top of a complex subsystem

    For example, an api module with getUser() and updateUser() hides fetch, headers, tokens, error handling and data transformation. The rest of the code doesn't know the details. A facade reduces coupling but shouldn't grow into a "god object".

  12. 12. What is the Proxy pattern used for?

    Correct answer: To control access to an object: caching, checks, laziness

    A proxy has the same interface as the original and intercepts access: lazy initialization, caching, validation, logging. JS has a built-in Proxy - Vue 3's reactivity is built on it.

  13. 13. Which pattern do for...of and Symbol.iterator implement?

    Correct answer: Iterator

    An iterator gives a uniform way to traverse a collection sequentially without exposing its internals. Arrays, Map, Set, strings and generators implement the iteration protocol, so they work the same in for...of and spread.

  14. 14. What is the Module pattern in JavaScript?

    Correct answer: Encapsulation: private details are hidden, a public API is exported

    Modules used to be made with IIFEs and closures; now ES modules are used: everything not exported is private. This reduces coupling and protects against name collisions in the global scope.

  15. 15. When is the Builder pattern useful?

    Correct answer: When an object is assembled step by step from many optional parts

    Instead of a constructor with ten parameters - a chain new QueryBuilder().select('id').where(...).limit(10).build(). Examples: SQL query builders (Knex), URL and config builders. In JS, passing an options object is often enough.

  16. 16. How is the Prototype pattern related to JavaScript?

    Correct answer: New objects are created from existing ones

    The Prototype pattern is about creating objects by cloning a sample. In JS, objects inherit from other objects via the prototype chain, and Object.create(proto) creates an object with a given prototype. A UI prototype (a mockup) is an entirely different concept.

  17. 17. What is the Command pattern used for?

    Correct answer: To represent an action as an object - for queues, logs and undo

    A command contains everything needed to perform an action and, if necessary, to undo it (execute/undo). This is how undo/redo in editors, operation queues and macros are implemented. Redux actions are a related idea: an action is described by an object.

  18. 18. Which pattern lets you treat a tree (a menu with submenus, a file system) uniformly?

    Correct answer: Composite

    Composite describes both leaves and containers with one interface, so the client traverses the tree without "is it a folder or a file" checks. The React component tree, the DOM and nested menus are natural examples.

  19. 19. What does the State pattern describe?

    Correct answer: An object changes behavior based on its state

    Instead of scattered if (status === ...) checks, each state's behavior is described separately, and transitions are explicit: idle → loading → success | error. On the frontend this idea is often implemented with state machines (XState) or useReducer with a discriminated union.

  20. 20. What does a Mediator do?

    Correct answer: Centralizes interaction between objects so they don't reference each other

    Form components don't call each other directly; they notify a mediator (the parent, a form controller), which decides what to change. This reduces "everyone with everyone" links. The risk is the mediator growing into an overly smart object.

  21. 21. Which pattern underlies middleware in Express or Redux?

    Correct answer: Chain of Responsibility

    A request passes through a sequence of handlers: each can handle it, modify it or pass it to the next via next(). This is how logging, authorization and body parsing are added without changing the main handler.

  22. 22. What is the Template Method pattern?

    Correct answer: A base algorithm whose steps subclasses override

    For example, a base class DataExporter defines export(): load → transform → save, and subclasses implement transform() for CSV and JSON. In a functional style, the same is done by passing step functions.

  23. 23. What is a Memento for?

    Correct answer: Saving an object's state so you can return to it later (undo)

    A memento stores state without exposing the object's internals. Change history in an editor or the Redux DevTools "time machine" are examples. With immutable data, a memento is simply a reference to a previous version.

  24. 24. Why do you need the Flyweight pattern?

    Correct answer: To save memory by sharing a common immutable part among many objects

    If 100,000 objects share a lot of identical data (an icon, a style, a type description), the shared part is stored once, and objects keep only their unique fields. JS strings and primitives partly use a similar technique.

  25. 25. What does the acronym SOLID stand for?

    Correct answer: Five object-oriented design principles by Robert Martin

    Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, Dependency Inversion. The principles apply beyond classes too: to functions, modules and React components.

  26. 26. What does the Single Responsibility Principle (SRP) require?

    Correct answer: A module should have one reason to change

    A component that loads data, formats it and draws a table changes for different reasons. Splitting it into a loading hook, formatting functions and a presentational component simplifies changes and tests. "One function" is a misreading.

  27. 27. What does the Open/Closed Principle (OCP) mean?

    Correct answer: Code is open for extension but closed for modification

    New behavior is added without rewriting proven code: via a new strategy, a plugin, or a component through props/children. Example: a Button with an icon prop instead of editing the button for every new icon.

  28. 28. What does the Liskov Substitution Principle (LSP) require?

    Correct answer: A subtype must be usable anywhere the base type is expected

    The classic violation: Square extends Rectangle, where setWidth also changes the height - code that relies on a rectangle breaks. On the frontend: a wrapper component around <input> should support expected props like onChange and disabled.

  29. 29. What is the Interface Segregation Principle (ISP) about?

    Correct answer: Clients shouldn't depend on methods and data they don't need

    An Avatar component that takes the whole user object with dozens of fields depends on too much. It's better to pass src and name. Narrow interfaces simplify reuse and tests.

  30. 30. What does the Dependency Inversion Principle (DIP) mean?

    Correct answer: High-level modules depend on abstractions, not on concrete implementations

    An order service depends on a PaymentGateway interface, not on a specific Stripe SDK. The implementation is passed in from outside, so it's easy to replace or mock in tests.

  31. 31. What does the DRY principle mean?

    Correct answer: Each piece of knowledge has a single representation

    Don't Repeat Yourself is about duplicated knowledge, not just similar lines. If an email validation rule is duplicated in three places, it's easy to miss one when it changes. But prematurely merging code that's similar yet different is harmful too.

  32. 32. What does the KISS principle mean?

    Correct answer: Keep it simple: avoid unnecessary complexity

    Keep It Simple, Stupid: a simple solution is easier to read, test and change. Complex abstractions are justified only when they solve a real problem. Short names and a single file aren't about simplicity.

  33. 33. What does the YAGNI principle mean?

    Correct answer: Don't implement functionality until it's actually needed

    You Aren't Gonna Need It: premature generality ("what if we need five languages") costs time and complicates code, and the assumptions often don't come true. It's not a ban on thoughtful architecture but a stance against "just in case" code.

  34. 34. What does "composition over inheritance" mean?

    Correct answer: Assemble behavior from parts instead of deep hierarchies

    Deep inheritance is fragile: a change in the base class breaks subclasses, and behavior gets "locked" into the hierarchy. Composition (functions, hooks, children, strategy objects) is more flexible. React explicitly recommends composition over component inheritance.

  35. 35. What does the MVC pattern describe?

    Correct answer: A split into model (data), view (UI) and controller (input handling)

    The model holds data and business logic, the view displays it, and the controller handles user actions and updates the model. Variants: MVP, MVVM. The idea of separating responsibilities lives on in the frontend: data separate from UI.

  36. 36. What is the Container/Presentational pattern in React about?

    Correct answer: The container handles data and logic, the presentational one only rendering

    Presentational components receive everything via props and are easy to reuse and test (e.g. in Storybook). Today the container role is often played by hooks, and in Next.js by server components that load data.

  37. 37. What pattern does a custom hook useWindowSize() implement?

    Correct answer: Reusing stateful logic without changing the component tree

    Hooks replaced HOCs and render props for reusing logic: the component calls a function and gets data without piling up wrappers. Inside, the hook subscribes to resize and unsubscribes itself (the Observer pattern).

  38. 38. Which pattern do React Context and <Provider> implement?

    Correct answer: Provider: a value becomes available to the whole subtree without passing props

    A provider solves prop drilling: the theme, current user and i18n are available to any descendant. There can be any number of contexts, and the same context can be provided with different values in different parts of the tree.

  39. 39. What is an anti-pattern?

    Correct answer: A popular solution that seems good but does harm

    Examples: the "god object", spaghetti code, magic numbers, copy-paste, premature optimization. Knowing anti-patterns helps you spot them in reviews and explain why a solution is bad.

  40. 40. What is a God Object?

    Correct answer: An object or component that knows and does too much

    A 2,000-line component, a utils service with everything in it - they're hard to understand, test and change, and any change is risky. The cure is splitting by responsibility (SRP).

  41. 41. What's wrong with "magic numbers" like if (status === 3)?

    Correct answer: The value's meaning is unclear

    A named constant ORDER_STATUS.SHIPPED explains the meaning and changes in one place. In TypeScript, a union of literals or an as const object is even better.

  42. 42. What is callback hell, and how is it avoided?

    Correct answer: Deeply nested async callbacks; solved with promises and async/await

    A "pyramid" of nested callbacks is hard to read and to handle errors in. Promises flatten the chain, and async/await makes async code look synchronous.

  43. 43. A function takes 7 arguments. Which refactoring is usually appropriate?

    Correct answer: Pass an options object with named fields

    A long parameter list is a "code smell": it's easy to mix up the order. An object with destructuring ({ id, title, onSave }) is self-documenting and allows default values. Sometimes it's a sign that the function does too much.

  44. 44. What is refactoring?

    Correct answer: Changing the structure of code without changing its behavior

    The goal is to make code clearer and easier to change. It's done in small steps under the protection of tests. If behavior changes, it's no longer refactoring but a functional change.

  45. 45. What is Separation of Concerns?

    Correct answer: Different aspects (data, logic, UI) live in different parts of the code

    For example, data loading lives in a hook or a server component, business rules in pure functions, rendering in components. A change in one aspect doesn't affect the others.

  46. 46. What does "high cohesion and low coupling" mean?

    Correct answer: One task inside a module, and modules depend on each other only loosely

    High cohesion means a module's parts work toward a common goal. Low coupling means modules communicate through narrow interfaces and don't know each other's details. Then changes stay local and don't ripple across the project.

  47. 47. What is Dependency Injection in its simplest form?

    Correct answer: Passing dependencies in from outside

    createOrderService({ api, logger }) instead of import api inside: it's easy to substitute mocks in tests, and the implementation can be replaced. In React, DI is often done via Context or props.

  48. 48. Which pattern does EventEmitter in Node.js or EventTarget in the browser implement?

    Correct answer: Observer

    The object keeps lists of handlers by event name and calls them on emit/dispatchEvent. Subscribing is on/addEventListener, unsubscribing is off/removeEventListener.

  49. 49. Why are pure functions useful in design?

    Correct answer: The result depends only on the arguments - they're easy to test

    A pure function without side effects is predictable: the same input gives the same output. It pays to move business logic (price calculation, validation) into pure functions and keep side effects at the edges of the system.

  50. 50. Which pattern does a HOC like withLogger(Component) use?

    Correct answer: Decorator

    A HOC wraps a component and adds behavior while keeping its interface - a classic decorator. The downsides of HOCs (nesting, prop conflicts) made hooks popular.

  51. 51. What is the render props pattern?

    <MouseTracker render={({ x, y }) => <Cursor x={x} y={y} />} />

    Correct answer: A component calls a function prop to decide what to render

    Custom hooks replaced most render props, but the pattern is still used where a component must control rendering, e.g. virtualized lists.

  52. 52. What are compound components?

    <Tabs>
      <Tabs.List><Tabs.Tab>One</Tabs.Tab></Tabs.List>
      <Tabs.Panel>Content</Tabs.Panel>
    </Tabs>

    Correct answer: Components that work together and share implicit state

    Users arrange the parts freely instead of passing a huge config object, like native <select> and <option>.

  53. 53. How does a controlled input differ from an uncontrolled one?

    Correct answer: A controlled input's value comes from props or state

    Controlled components are easier to validate and sync; uncontrolled ones are simpler and can be read with a ref or FormData.

  54. 54. What does replacing nested ifs with guard clauses give you?

    function pay(order) {
      if (!order) return;
      if (order.paid) return;
      charge(order);
    }

    Correct answer: Edge cases exit early, reducing nesting

    Early returns make the "happy path" read top to bottom and keep the indentation flat.

  55. 55. How can a long switch that maps a status to a label be simplified?

    const labels = { draft: 'Draft', published: 'Published', archived: 'Archived' };
    const label = labels[status];

    Correct answer: Replace it with a lookup object

    Data-driven mapping is shorter and easier to extend. When each case has different behavior, objects with a shared method (polymorphism) fit better.

  56. 56. What is the Extract Function (Extract Method) refactoring?

    Correct answer: Moving code into a separate, well-named function

    A good name replaces a comment and makes the fragment reusable and testable on its own.

  57. 57. What does the Bridge pattern separate?

    Correct answer: An abstraction from its implementation

    Instead of SvgCircle, CanvasCircle, SvgSquare... you combine any shape with any renderer, avoiding a class explosion.

  58. 58. Why is a very long function considered a code smell?

    Correct answer: It's hard to understand, test and reuse

    If you need comments to explain sections, those sections are candidates for extracted functions.

  59. 59. What should you do with dead code (unused functions, unreachable branches)?

    Correct answer: Delete it; version control keeps the history

    Dead code confuses readers, gets "maintained" for nothing and can be bundled to users.

  60. 60. Which comments are most valuable?

    Correct answer: Those that explain why something is done

    If a comment explains what code does, clearer names or an extracted function usually make it unnecessary.

  61. 61. Which name is best for a boolean variable?

    Correct answer: isModalOpen

    Prefixes like is, has, can, should make conditions read like sentences: if (isModalOpen).

  62. 62. Why prefer creating new objects over mutating existing ones in UI state?

    Correct answer: Change detection becomes a cheap reference check

    React, Redux and many tools rely on reference changes to detect updates.

  63. 63. What is encapsulation?

    Correct answer: Hiding internal details behind a public interface

    Private fields (#count), module-private functions and closures let internals change without breaking callers.

  64. 64. What is polymorphism?

    Correct answer: Working with different types through one interface

    Calling shape.area() works for circles and squares without checking which one it is.

  65. 65. What's the difference between "is-a" and "has-a" relationships?

    Correct answer: "Is-a" suggests inheritance; "has-a" composition

    If the relationship is really "has-a" or "uses-a", inheritance creates unnecessary coupling.

  66. 66. How do debounce and throttle differ?

    Correct answer: Debounce waits for a pause; throttle limits the rate

    Debounce suits search-as-you-type; throttle suits scroll or resize handlers that must update periodically.

  67. 67. What is an optimistic UI update?

    Correct answer: Showing the expected result, with rollback on failure

    It makes likes and toggles feel instant. It needs a rollback path and is unsuitable for actions that rarely succeed or can't be undone.

  68. 68. What is lazy loading?

    Correct answer: Loading code or data only when it's needed

    Examples: import() for routes, loading="lazy" for images. It reduces initial load at the cost of a delay later.

  69. 69. What are feature flags (feature toggles)?

    Correct answer: Switches that toggle features without redeploying

    They allow gradual rollouts, A/B tests and quick kill switches, but old flags must be removed to avoid clutter.

  70. 70. What's the purpose of a fallback UI (e.g. a React error boundary)?

    Correct answer: To show a message instead of crashing the whole app

    Placing boundaries around independent widgets keeps the rest of the page usable.

  71. 71. What does it mean that an operation is idempotent?

    Correct answer: Repeating it gives the same result as doing it once

    Idempotent operations are safe to retry after timeouts. "Add 1" isn't idempotent; "set to 5" is.

  72. 72. What does "single source of truth" mean for app data?

    Correct answer: Each piece of data is stored in one place

    Copies drift apart. Compute derived values instead of storing them separately.

  73. 73. What is a config-driven (data-driven) UI?

    const fields = [
      { name: 'email', type: 'email', required: true },
      { name: 'age', type: 'number' },
    ];

    Correct answer: UI generated from a description in data

    It suits repetitive structures like forms or tables. For unique screens, plain components are easier to read.

  74. 74. What does the Principle of Least Astonishment say?

    Correct answer: Code should behave the way readers expect

    A function getUser() shouldn't also send emails; a "Cancel" button shouldn't save. Surprises cause bugs.

  75. 75. What does "premature optimization is the root of all evil" warn against?

    Correct answer: Complicating code before measuring a bottleneck

    Measure first (profiler, Web Vitals), then optimize the hot spots. Obvious algorithmic problems are still worth avoiding from the start.