DEV Community

CodeWithDhanian
CodeWithDhanian

Posted on

2

JavaScript Design Patterns Every Developer Should Know

by Code with Dhanian
Get the Full JavaScript eBook Here »

When building scalable, maintainable, and efficient JavaScript applications, understanding design patterns is crucial. These patterns offer proven solutions to common coding problems and help developers write cleaner, modular, and reusable code. Whether you're a beginner or an experienced developer, learning JavaScript design patterns will significantly improve how you structure your code.

In this article, we'll explore the most essential JavaScript design patterns every developer should know.

1. Singleton Pattern

The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it.

Use Case: Managing global application state, configuration objects, or database connections.

const AppConfig = (function () {
  let instance;

  function createInstance() {
    return { theme: 'dark', version: '1.0' };
  }

  return {
    getInstance: function () {
      if (!instance) instance = createInstance();
      return instance;
    }
  };
})();

const config1 = AppConfig.getInstance();
const config2 = AppConfig.getInstance();
console.log(config1 === config2); // true
Enter fullscreen mode Exit fullscreen mode

2. Module Pattern

The Module Pattern encapsulates related code into a single unit and exposes only what’s necessary, using closures.

Use Case: Encapsulating logic to keep global scope clean.

const CounterModule = (function () {
  let count = 0;

  return {
    increment() {
      count++;
      return count;
    },
    reset() {
      count = 0;
      return count;
    }
  };
})();

CounterModule.increment(); // 1
CounterModule.increment(); // 2
CounterModule.reset();     // 0
Enter fullscreen mode Exit fullscreen mode

3. Factory Pattern

The Factory Pattern allows the creation of objects without exposing the creation logic to the client.

Use Case: Creating different types of objects based on input conditions.

function CarFactory(type) {
  switch (type) {
    case 'sedan':
      return { wheels: 4, doors: 4, type: 'sedan' };
    case 'truck':
      return { wheels: 6, doors: 2, type: 'truck' };
    default:
      return { wheels: 4, doors: 4, type: 'default' };
  }
}

const car = CarFactory('truck');
console.log(car); // { wheels: 6, doors: 2, type: 'truck' }
Enter fullscreen mode Exit fullscreen mode

4. Observer Pattern

The Observer Pattern defines a subscription mechanism to notify multiple objects about events.

Use Case: Event-driven architecture or reactive UIs.

class EventEmitter {
  constructor() {
    this.events = {};
  }

  on(event, listener) {
    if (!this.events[event]) this.events[event] = [];
    this.events[event].push(listener);
  }

  emit(event, data) {
    if (this.events[event]) {
      this.events[event].forEach(listener => listener(data));
    }
  }
}

const emitter = new EventEmitter();
emitter.on('save', (data) => console.log(`Data saved: ${data}`));
emitter.emit('save', 'Project Info');
Enter fullscreen mode Exit fullscreen mode

5. Prototype Pattern

The Prototype Pattern lets you create new objects based on an existing object’s blueprint.

Use Case: Efficient memory usage and object inheritance in JavaScript.

const vehicle = {
  wheels: 4,
  start() {
    console.log('Vehicle started');
  }
};

const car = Object.create(vehicle);
car.start(); // Vehicle started
Enter fullscreen mode Exit fullscreen mode

6. Command Pattern

The Command Pattern encapsulates a request as an object, allowing parameterization and queuing.

Use Case: Undo/Redo functionality, task queues.

function commandReceiver() {
  return {
    execute(action) {
      console.log(`Executing ${action}`);
    }
  };
}

const receiver = commandReceiver();
const command = { execute: () => receiver.execute('Save Document') };
command.execute();
Enter fullscreen mode Exit fullscreen mode

Final Thoughts

Mastering these JavaScript design patterns helps you build more maintainable and scalable applications. Whether you’re working on large-scale web apps or personal projects, these patterns provide structure and clarity to your codebase.

Want to dive deeper into JavaScript with real-world projects and advanced patterns?
Get my full JavaScript eBook with 200+ pages of content, code examples, and hands-on projects:

Download the eBook Now »

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (1)

Collapse
 
ganesh_kumar_e4e98249188e profile image
ganesh kumar

Useful guide on JavaScript design patterns! Developers can also boost their programming skills with this Java Course in Coimbatore.

Visit - appincoimbatore.com/java-course-in...

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!

Join the Runner H "AI Agent Prompting" Challenge: $10,000 in Prizes for 20 Winners!

Runner H is the AI agent you can delegate all your boring and repetitive tasks to - an autonomous agent that can use any tools you give it and complete full tasks from a single prompt.

Check out the challenge

DEV is bringing live events to the community. Dismiss if you're not interested. ❤️