Skip to main content

Command Palette

Search for a command to run...

Best Practices and Design Patterns in JavaScript

Published
โ€ข2 min read
Best Practices and Design Patterns in JavaScript
I

Welcome to my digital playground! ๐Ÿš€ Hey there, I'm Ciprian ๐Ÿ‘‹ โ€“ a 42-year-old digital creator and coding enthusiast based in Bucharest. My world revolves around crafting exceptional digital experiences and living the #NerdLife ๐Ÿค“โœจ.

๐ŸŒŸ What I'm About: By day: I'm a Test Engineer brewing endless cups of coffee โ˜• and tackling challenges with a keen eye for detail. By night: I transform into a passionate coder ๐ŸŒ™, diving into fullstack development and exploring the limitless world of tech. Gym enthusiast ๐Ÿ’ช: Balancing code and caffeine with fitness. Streamer: I stream my nerdy adventures in gaming and coding ๐ŸŽฎ โ€“ join me on this journey! ๐Ÿ”ญ My Current Endeavors: Leading and learning in full-stack development projects, constantly pushing the boundaries. Experimenting with diverse tools and libraries, ever-expanding my tech toolkit. An early riser and lifelong learner, thriving in the fast-paced tech landscape. โœจ A Glimpse Into My World: Childhood dream: Surgeon โ€“ now healing bugs in code! A proud Mac user, having made the leap from Windows. Always exploring, always engaging, always evolving. ๐Ÿ“ซ Let's Connect: For daily updates and a peek into my life, follow me on Instagram and LinkedIn. Keen on my professional journey? Let's connect on LinkedIn and YouTube. For a deeper dive, check out my blog and website. Want to talk tech or just say hi? DM me on Instagram or LinkedIn. For professional collaborations, drop an email at ionutcipriananescu@gmail.com. Dive into my repository and explore my VS Code Configuration for development optimization.

Join me in this adventure where technology meets creativity, one line of code at a time!

This document provides an overview of some key best practices and design patterns in JavaScript, aimed at improving code organization, maintainability, and scalability. We'll explore the Singleton, Factory, Observer, and Module patterns with JavaScript code examples.

Table of Contents

Singleton Pattern

The Singleton Pattern ensures that a class has only one instance and provides a global point of access to it. It's useful for managing resources such as database connections.

let instance = null;

class Database {
  constructor() {
    if (!instance) {
      instance = this;
    }
    // Initialize connection
    return instance;
  }

  connect() {
    // Connection logic
  }
}

// Usage
const db1 = new Database();
const db2 = new Database();
console.log(db1 === db2); // true

Factory Pattern

The Factory Pattern is a creational design pattern that provides an interface for creating objects in a superclass, but allows subclasses to alter the type of objects that will be created.

class Dog {
  speak() {
    return 'Woof!';
  }
}

class Cat {
  speak() {
    return 'Meow!';
  }
}

function getPet(petType) {
  const pets = {
    dog: new Dog(),
    cat: new Cat(),
  };
  return pets[petType];
}

// Usage
const dog = getPet('dog');
console.log(dog.speak()); // Woof!

const cat = getPet('cat');
console.log(cat.speak()); // Meow!

Observer Pattern

The Observer Pattern is a behavioral design pattern where an object, known as the subject, maintains a list of its dependents, called observers, and notifies them of state changes.

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

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

  unsubscribe(observer) {
    this.observers = this.observers.filter(sub => sub !== observer);
  }

  notify(data) {
    this.observers.forEach(observer => observer.update(data));
  }
}

class Observer {
  update(data) {
    console.log(`Observer received data: ${data}`);
  }
}

// Usage
const subject = new Subject();
const observer = new Observer();

subject.subscribe(observer);
subject.notify('Hello World!'); // Observer received data: Hello World!

Module Pattern

The Module Pattern encapsulates "private" and "public" members separately to shield parts of the code from the global scope and avoid potential name clashes.

const myModule = (() => {
  const privateVar = 'I am private';
  return {
    publicMethod: () => `The public can see me and ${privateVar}`,
  };
})();

// Usage
console.log(myModule.publicMethod()); // The public can see me and I am private

Conclusion

Using these design patterns and best practices can significantly enhance the quality, scalability, and maintainability of your code in JavaScript projects. They encourage a cleaner, more organized codebase, making it easier for teams to develop and manage complex applications.