How to do a Singleton in JavaScript

How to do a Singleton in JavaScript

Learn how to generate a Singleton in JavaScript / Typescript

ยท

1 min read

What it is

"The singleton pattern is a software design pattern that restricts the instantiation of a class to one "single" instance. This is useful when exactly one object is needed to coordinate actions across the system."

How to implement it

You can generate a Singleton in JavaScript very easily using Modules, E.g:

class DataBase {
  constructor() {
    DBDriver.connect();
  }

  async getLink(id) {
    // Do stuff
  }

  async deleteByID(id) {
    // Do other stuff
  }
}

export default new DataBase();

Yes, an ESM/CommonJS module is guaranteed to return the same instance, every time you import it.

While this might be sound bad, because it is a mutable global state, it is very handy in this case.

An alternative

Also if you class don't use this, doesn't have a constructor, or all their methods are static, consider using a literal object. Eg:

const DataBaseTwo = {
  getLink(id){
    // Do stuff
  },

  deleteByID(id){
    // Do other stuff
  },
};

export default DataBaseTwo;

There is an eslint rule for this if you want.

ย