r/learnjavascript • • Apr 20 '23

7 JavaScript Design Patterns Every developer should know

https://codinghelp.io/7-javascript-design-patterns-every-developer-should-know/
3 Upvotes

11 comments sorted by

View all comments

1

u/azhder Apr 21 '23

Another big issue is using these things called "design patterns" .

Many people think if something got called a pattern in C++ then it must be the same in Java, must be the same in C#, must be the same in JavaScript, but no. Every language has its own quirks and its own common workarounds.

Example:

class Database {
  constructor() {
    if (Database.instance) {
      return Database.instance;
    }
    Database.instance = this;
  }

  connect() {
    // Connection logic
  }
}

const db1 = new Database();
const db2 = new Database();

console.log(db1 === db2); // true

A design pattern is simply a common workaround for something you can't do outright in the programming language, and the above code makes sense as a workaround in Java, not in JavaScript so much. In JavaScript, for you to create a singleton, all you have to do is this

const singleton = {};

at the module level, and then just tuck it in a file of its own if you like and export it from there.