design patterns in javascript with examples

JavaScript Design Patterns with Examples: Master Reusable Code Solutions

By Steven Jackson
AD

Design patterns in JavaScript offer a structured approach to solving common programming challenges, providing reusable solutions that enhance code readability and maintainability. By leveraging these proven templates, developers can write more predictable and scalable applications, reducing the likelihood of bugs and improving team collaboration. Instead of reinventing the wheel for every feature, these patterns act as blueprints tailored to the dynamic nature of JavaScript.

Understanding the Core Concept

A design pattern is essentially a general repeatable solution to a commonly occurring problem in software design. It is not a finished design that can be transformed directly into code but rather a description or template for how to solve a problem that can be used in many different situations. In JavaScript, these patterns are particularly valuable due to the language's flexible, prototype-based inheritance and first-class functions.

Unlike frameworks, which dictate structure, design patterns are conceptual tools that guide the architecture of your code. They help you think about potential pitfalls and future changes during the development phase itself. Recognizing when to apply a specific pattern separates intermediate coders from those who engineer robust, long-term solutions.

AD
JavaScript Design Patterns
JavaScript Design Patterns
Learn About the Decorator Design Pattern in JavaScript
Learn About the Decorator Design Pattern in JavaScript
a block diagram showing the different types of food items
a block diagram showing the different types of food items

The Singleton Pattern

Ensuring a Single Instance

The Singleton pattern ensures that a class has only one instance and provides a global point of access to it. This is useful for managing shared resources like configuration settings or connection pools, where having multiple instances could lead to inconsistencies or performance issues.

In JavaScript, this is often implemented using an Immediately Invoked Function Expression (IIFE) or by leveraging static properties within ES6 classes to store the single instance.

A Quick Module Design Pattern Example in JavaScript
A Quick Module Design Pattern Example in JavaScript
explore stunning graphics made with javascript
explore stunning graphics made with javascript
Javascript Cheet cheet
Javascript Cheet cheet
const Singleton = (function() {
  let instance;
  function createInstance() {
    const object = new Object("I am the instance");
    return object;
  }
  return {
    getInstance: function() {
      if (!instance) {
        instance = createInstance();
      }
      return instance;
    }
  };
})();

const instance1 = Singleton.getInstance();
const instance2 = Singleton.getInstance();
console.log(instance1 === instance2); // true

The Factory Pattern

Creating Objects Without Specifying the Exact Class

The Factory pattern provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created. It is particularly useful when the creation process is complex or when you want to abstract the instantiation logic away from the consumer.

This pattern promotes loose coupling by eliminating the need to bind application-specific classes into the code. The code that uses the factory only needs to know the interface it returns, not the concrete implementation details.

AD
function CarFactory() {}

CarFactory.prototype.create = function(type) {
  switch(type) {
    case "sports":
      return new SportsCar();
    case "family":
      return new FamilyCar();
    default:
      throw new Error("Invalid car type");
  }
};

function SportsCar() { this.speed = "fast"; }
function FamilyCar() { this.space = "spacious"; }

const factory = new CarFactory();
const myCar = factory.create("sports");
console.log(myCar.speed); // "fast"

The Module Pattern

Encapsulation and Privacy

Inspired by the concept of modules in software engineering, this pattern leverages JavaScript's function scope to create private and public members. Before the advent of ES6 classes, this was the primary method to achieve encapsulation in JavaScript.

How to Create Reusable Code In JavaScript Using Design Patterns
How to Create Reusable Code In JavaScript Using Design Patterns
Dr Milan Milanović (@milan_milanovic) on X
Dr Milan Milanović (@milan_milanovic) on X
an info sheet with different types of web pages
an info sheet with different types of web pages
the web programming poster is shown
the web programming poster is shown
Coding with Parvez
Coding with Parvez
Exploring 2D differential growth with JavaScript
Exploring 2D differential growth with JavaScript

By returning an object that contains references to inner functions, you create a public API while keeping variables and helper methods safely hidden within the closure. This prevents global namespace pollution and protects data integrity.

const Counter = (function() {
  let count = 0; // Private variable

  function change(val) { // Private function
    count += val;
  }

  return { // Public API
    increment: function() {
      change(1);
    },
    getCount: function() {
      return count;
    }
  };
})();

Counter.increment();
console.log(Counter.getCount()); // 1
// console.log(Counter.count); // Undefined

The Observer Pattern

Event Handling and Pub/Sub

The Observer pattern defines a one-to-many dependency between objects so that when one object changes state, all its dependents are notified automatically. This is a fundamental pattern for implementing event handling systems and reactive programming in JavaScript.

AD

It decouples the subject (the entity holding the data) from the observers (the entities reacting to the data), allowing for dynamic subscription models. This is the underlying logic behind Node.js events and many frontend frameworks' state management systems.

JavaScript Array Methods Cheat Sheet — The Only Guide You Need
JavaScript Array Methods Cheat Sheet — The Only Guide You Need
JavaScript Works in the Browser
JavaScript Works in the Browser
'Patterns.dev' - Learn design, rendering, and performance patterns for building web apps with JavaScript for free
'Patterns.dev' - Learn design, rendering, and performance patterns for building web apps with JavaScript for free
Wallpaper JavaScript
Wallpaper JavaScript
a group of blue birds flying through the air
a group of blue birds flying through the air
Generative Art with JavaScript and SVG by David Matthew | Indigo Chapters
Generative Art with JavaScript and SVG by David Matthew | Indigo Chapters
Design Patterns: Learning Abstract Factory Method through real life examples
Design Patterns: Learning Abstract Factory Method through real life examples
javaScript tutorial
javaScript tutorial
an image of a computer program with numbers and symbols
an image of a computer program with numbers and symbols
javascript
javascript
Java design patterns
Java design patterns
How To Crop Images In Javascript
How To Crop Images In Javascript
20 Customizable Header Styles #dynamicliquids #uiux
20 Customizable Header Styles #dynamicliquids #uiux
function EventEmitter() {
  this.events = {};
}

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

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

const emitter = new EventEmitter();
emitter.on('greet', name => console.log(`Hello, ${name}!`));
emitter.emit('greet', 'Alice'); // "Hello, Alice!"

When to Apply These Patterns

Selecting the right pattern depends heavily on the context of your application. While the Singleton is excellent for logging utilities, it might be an anti-pattern in testing environments where isolation is key. Similarly, the Factory shines when dealing with complex object creation hierarchies, but might be overkill for simple instantiation logic.

Understanding the trade-offs is crucial. Patterns introduce structure, but they also add complexity. Use them to solve actual problems rather than as a checkbox exercise. The goal is clean, understandable code, not an architecture that is difficult to follow.

AD
AD