Skip to main content
← Back to Blog
2026-02-21 · 7 min readWeb DevelopmentUpdated Oct 29, 2026

Architecting Scalable JavaScript: OOP Principles & Design Patterns

When a script grows into a system, structure matters. This guide covers encapsulation with private class fields, the Module pattern with ES modules, the Singleton pattern (and why a module export is often enough), and the Observer pattern with unsubscribe. It ends with a bot controller that combines all three, built on EventTarget.

Avnish Yadav
AI Automation Engineer & Salesforce Developer
2 views
Architecting Scalable JavaScript: OOP Principles & Design Patterns

A 50-line script that scrapes one page doesn't need architecture. An automation tool that manages state, calls several APIs and reacts to events does, or it turns into spaghetti fast. This guide is for JavaScript developers whose scripts are growing into systems. You'll learn how to hide internal state with private class fields, then three design patterns (Module, Singleton and Observer), and finally how to combine them in a small bot controller. Every snippet runs in a current Node.js LTS (19 or later for the global CustomEvent); save files that use export as .mjs.

This is part 8 of the Frontend & JavaScript Fundamentals series. It builds on prototypes and ES6 classes, which showed what a class is underneath.

Key takeaways

  • Hide state with #private fields and module scope; expose only the methods other code needs.
  • A Singleton is shared global state: use it for infrastructure such as logging and config, and often a module export is enough.
  • The Observer pattern lets one part of the system announce events without knowing who listens, so you add features without editing the sender.

From scripts to systems

JavaScript supports several styles. Functional code is a natural fit for transforming data. Classes are useful when you model things that hold state and have a lifecycle, such as agents, managers and connectors.

The previous part showed that classes run on prototypes. That doesn't make them a bad choice. It means you know what they cost and what they give you: a clear place for state and the methods that change it.

A design pattern is a reusable, named solution to a common structural problem in code. Knowing the names helps teams talk about structure without walking through every line.

Encapsulation with private class fields

Encapsulation means an object keeps its internal state hidden and offers methods for working with it. In older code, an underscore (_apiKey) only signalled "please don't touch". Private class fields, written with #, are enforced by the language. MDN notes that referring to a # name from outside the class is a syntax error.

class AgentConfig {
  #apiKey;

  constructor(key) {
    this.#apiKey = key;
  }

  getSafeConfig() {
    return {
      status: 'active',
      // The key itself never leaves the class
      hasKey: !!this.#apiKey
    };
  }
}

const config = new AgentConfig('test-key-not-real');
console.log(config.getSafeConfig()); // { status: 'active', hasKey: true }
console.log(Object.keys(config)); // []

Private is not secret

#private stops other code from reading or changing the field by accident. It isn't a security boundary. MDN notes that Chrome DevTools can read private elements, and anyone can read the JavaScript you send to a browser. Keep real API keys on a server.

1. The Module pattern

The Module pattern splits code into units that keep their details private and expose a small public API. Patterns.dev puts it this way: "A module is a file that owns a piece of behavior, decides what to share, and keeps everything else to itself."

Before ES modules, developers built this with an immediately invoked function expression (IIFE) and a closure. Today the language does it for you: anything a file doesn't export stays inside that file. MDN's modules guide says module variables are scoped to the module, not the global scope.

// database-connector.js (the module)
const dbConfig = {
  host: 'localhost',
  retries: 3
};

// Private: not exported, so other files can't call it
function connect() {
  console.log(`Connecting to ${dbConfig.host}...`);
}

// Public API
export class DatabaseService {
  constructor() {
    connect();
  }

  query(sql) {
    console.log(`Executing: ${sql}`);
    return [];
  }
}

In an automation project, you might have separate areas for content generation, social posting and analytics. Give each one its own module, and the posting code can't reach into the content module's settings by accident.

2. The Singleton pattern

The Singleton pattern makes sure there is only one instance of something and gives the whole app access to it. Patterns.dev describes it as an object that exists exactly once for the life of your application. Typical uses are infrastructure: a logger, a config store or a database connection pool. You don't want a new pool for every request.

Here is a class that returns the same instance every time:

class Logger {
  constructor() {
    if (Logger.instance) {
      return Logger.instance;
    }

    this.logs = [];
    Logger.instance = this;

    // Stop other code from adding or replacing properties
    Object.freeze(this);
  }

  log(message) {
    const timestamp = new Date().toISOString();
    this.logs.push({ timestamp, message });
    console.log(`[${timestamp}] ${message}`);
  }

  getHistory() {
    return this.logs;
  }
}

const loggerA = new Logger();
const loggerB = new Logger();

loggerA.log("System init");

console.log(loggerA === loggerB); // true
console.log(loggerB.getHistory().length); // 1

Object.freeze(this) stops anyone replacing logs, but the array itself can still grow, which is what log() needs.

In JavaScript you often don't need the class at all. MDN's modules guide says a module runs only once, so every file that imports it gets the same object:

// logger.js: the module itself is the single instance
const logs = [];

export const logger = {
  log(message) {
    logs.push({ timestamp: new Date().toISOString(), message });
  },
  count() {
    return logs.length;
  },
};

Use Singletons sparingly. They are global state, and Patterns.dev warns that a Singleton keeps its state across tests, which can make tests depend on their order. A good default is to keep them for infrastructure such as logging, the database and config, and never for business data such as one user's session.

3. The Observer pattern

Automation is often event-driven: "when a new lead arrives, alert Slack, add it to the CRM and send an email." If the lead code calls each of those directly, every new step means editing it.

The Observer pattern fixes that. Patterns.dev defines it as a subject that keeps a list of observers and tells them when something changes. The subject doesn't know who's listening.

class EventManager {
  constructor() {
    this.listeners = new Map();
  }

  subscribe(eventType, callback) {
    if (!this.listeners.has(eventType)) {
      this.listeners.set(eventType, new Set());
    }
    this.listeners.get(eventType).add(callback);
    // Return a function that removes this listener again
    return () => this.listeners.get(eventType).delete(callback);
  }

  notify(eventType, data) {
    for (const callback of this.listeners.get(eventType) ?? []) {
      callback(data);
    }
  }
}

// The subject, for example a lead capture form
class LeadSystem {
  constructor(eventManager) {
    this.events = eventManager;
  }

  newLead(leadData) {
    console.log("New lead received.");
    // It doesn't know what happens next; it just announces the event
    this.events.notify('lead:created', leadData);
  }
}

const events = new EventManager();
const crm = new LeadSystem(events);

// Observer 1: Slack alert
const stopSlack = events.subscribe('lead:created', (data) => {
  console.log(`[Slack Bot]: Sending alert for ${data.name}`);
});

// Observer 2: welcome email
events.subscribe('lead:created', (data) => {
  console.log(`[Email Bot]: Queuing welcome email to ${data.email}`);
});

crm.newLead({ name: "Priya", email: "priya@acme.test" });

stopSlack(); // Slack alerts are off from here on
crm.newLead({ name: "Sam", email: "sam@acme.test" });

When you later need "add the lead to Google Sheets", you don't touch LeadSystem. You subscribe one more observer. Strictly, EventManager is a small pub/sub channel: LeadSystem publishes to it instead of holding observers itself. Either way, this is the open/closed principle: open for extension, closed for modification.

Patterns.dev's Observer page gives two cautions. Every subscription is a reference from the subject to the observer, so an observer you never unsubscribe can't be garbage collected; that's why subscribe() returns an unsubscribe function. And notify runs every observer synchronously, so one slow observer delays the rest.

You rarely need to write this class yourself. Node.js ships EventEmitter, whose docs say it calls listeners synchronously in the order they were added. Browsers and Node.js both have EventTarget, which the next section uses.

Fixed in this version

The earlier event manager had no way to unsubscribe, which leaks listeners in long-running bots. The bot controller below also called scraper.on() on a class that never defined it; it now extends EventTarget.

The three patterns side by side

Pattern What it does Trade-off When to use
Module Hides details, exports a small API More files and import wiring Every feature area
Singleton One shared instance for the whole app Global state; harder to test Logger, config, connection pool
Observer Senders announce events; listeners react Leaks if you don't unsubscribe; harder to trace Workflows where steps get added over time

Putting it together: a bot controller

Here's how the three fit in a small bot. A frozen config object plays the Singleton. Each agent is its own class (in a real project, its own module). The scraper announces finished work as an event, and the writer reacts.

// Config: one shared, read-only object (a module-level Singleton)
const botConfig = Object.freeze({ targetUrl: 'https://news.ycombinator.com/' });

// Scraper: announces results as events
class ScraperAgent extends EventTarget {
  start(url) {
    // A real scraper would fetch and parse the page here
    const content = `Headlines from ${url}`;
    this.dispatchEvent(new CustomEvent('data-scraped', { detail: content }));
  }
}

// Writer: knows nothing about the scraper
class WriterAgent {
  draftPost(content) {
    console.log(`Drafting a post from: ${content}`);
  }
}

// Orchestration
class BotController {
  constructor(config) {
    this.config = config;
    this.scraper = new ScraperAgent();
    this.writer = new WriterAgent();
  }

  init() {
    this.scraper.addEventListener('data-scraped', (event) => {
      this.writer.draftPost(event.detail);
    });

    this.scraper.start(this.config.targetUrl);
  }
}

new BotController(botConfig).init();

ScraperAgent extends EventTarget, so it gets addEventListener() and dispatchEvent() for free. MDN's CustomEvent page says the detail property carries the data you attach. The controller receives the config as an argument instead of importing it, which makes it easy to pass a test config.

Patterns are tools for complexity

Design patterns aren't academic theory. They're names for structures that keep growing code readable. Start small: next time you need shared config, export one object from a module. Next time two functions are tightly coupled, try an event.

Next in the series, essential web APIs and browser internals covers the browser features that code like this runs on.

Frequently asked questions

Is the Singleton pattern an anti-pattern?

Not always, but it is global state. Patterns.dev points out that it carries state across tests and hides dependencies. Keep it for infrastructure such as logging or config, and pass it in as an argument where you can.

Do I need classes to use design patterns in JavaScript?

No. The Module pattern is built into ES modules, and a Singleton can be a plain exported object. Classes help when an object has state and a lifecycle, such as an agent or a connection.

What is the difference between the Observer pattern and pub/sub?

In the Observer pattern, observers subscribe to the subject directly. In publish/subscribe, a separate event channel sits between them, so publishers and subscribers don't know about each other. The EventManager above works like a small pub/sub channel.

Should I use EventEmitter or EventTarget?

Use EventTarget if the code must run in both browsers and Node.js. Use EventEmitter in Node-only code, where many libraries already use it. Both cover the Observer pattern, so you rarely need your own event class.

Sources

Verified against the sources below on October 29, 2026. Products and docs change often: check the linked sources if something looks different.

  1. MDN: Private elements
  2. MDN: JavaScript modules
  3. Patterns.dev: Module pattern
  4. Patterns.dev: Singleton pattern
  5. Patterns.dev: Observer pattern
  6. Node.js: Events (EventEmitter)
  7. MDN: EventTarget
  8. MDN: CustomEvent
All 30 parts in this series
  1. Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
  2. Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
  3. Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
  4. Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
  5. Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
  6. Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
  7. Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
  8. Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
  9. Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
  10. Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
  11. Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
  12. Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
  13. Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
  14. Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
  15. Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
  16. Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
  17. Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
  18. Part 18Getting Started with React: Deconstructing JSX and Component Architecture
  19. Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
  20. Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
  21. Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
  22. Part 22React Architecture: Advanced Navigation and Data Flow Patterns
  23. Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
  24. Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
  25. Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
  26. Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
  27. Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
  28. Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
  29. Part 29Introduction to Micro Frontends: Building Scalable Architectures
  30. Part 30The Frontend Architecture: From Junior Developer to Tech Lead
Written by

Avnish Yadav

AI Automation Engineer & Salesforce Developer

Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.

About meLinkedIn

Share
Discussion

Comments

Loading comments...

Add a comment

Comments are reviewed before they appear.