JavaScript Design Patterns You Should Know!

JavaScript Design Patterns You Should Know!

·

3 min read

Design patterns are reusable solutions to common software design problems. They help make code more maintainable, extensible and reusable by documenting best practices used to solve typical problems. Here are some important JavaScript design patterns every developer should learn.

Module Pattern

The Module pattern separates private variables and functions from public variables and functions by encapsulating them within a single object. This helps avoid variable collisions and exposes only an object with public methods.

The basic Module pattern looks like this:

const module = (function () {
  let privateVar = 'some value';

  function privateFunction() {
    // ... use privateVar here
  }

  return {
    publicProperty: 'some value',
    publicMethod: function () {
      privateFunction();
    }
  }
})();

We wrap related functions and variables in a self-executing function, which acts as a closure to expose only what's returned from it. This creates private and public scopes. The public scope can access private variables and functions, but not vice versa.

Advantages:

• Hiding inner implementation details
• Exposing public variables and functions
• Avoiding global namespace pollution
• Reusing code across modules

Module pattern examples include utility libraries and class implementations.


Factory Pattern

The Factory pattern defines a method to create objects without exposing object creation logic. It allows abstracting object creation and decoupling classes that require objects.

A basic factory function:

function createEmployee(type) {
  if (type === 'engineer') {
     return new Engineer();  
  }
  if (type === 'manager') {
     return new Manager();  
  }
}

const emp1 = createEmployee('engineer');
const emp2 = createEmployee('manager');

Here we pass an employee type to determine the subclass to create. This decouples client code from implementation subclasses.

Advantages:

• Hides object creation logic
• Reduces conditional statements
• Loosely couples classes using objects
• Supports open/closed principle

You can create Object, Class and Constructor factories in JavaScript.


Observer Pattern

The Observer pattern defines a subscription mechanism where objects (observers) subscribe to an event source (subject) to be notified of state changes. When a subject's state changes, all observers are notified.

class Subject {
  constructor() {
     this.observers = [];  
  }

  attach(observer) {
    this.observers.push(observer);
  }  
}

class Observer {
  update() { /*..*/ }
}

Here the Subject maintains a list of Observer objects. When an event occurs, it notifies all observers by calling their update() method.

This pattern has advantages like:

• Loose coupling between subjects and observers
• Supports open/closed principle
• Handles many-to-many relationships
• Enables broadcast communication


Other useful patterns:

• Singleton - Creates only one object instance across an app.
• Strategy - Defines a family of interchangeable algorithms.
• Prototype - Creates objects by cloning a prototype instance.
• Mediator - Acts as a centralized hub that coordinates interactions.

Mastering these common JavaScript design patterns will help you:

• Reuse code across projects
• Reduce coupling between classes
• Achieve more modular, flexible and extensible code
• Apply object-oriented principles to JavaScript

Learning these patterns will make your JavaScript more future-proof and maintainable.

Did you find this article valuable?

Support Lexy by becoming a sponsor. Any amount is appreciated!