DEV Community


Discussion on: Singleton in JavaScript

bgadrian profile image
Adrian B.G.

While, by some, seen as an anti-pattern, it is worth knowing something about it.

Everyone should see it like that, I think it is even mentioned in antipattern book. The good thing is that most of its downsides can be avoided by allowing anyone to make an instance (making the constructor public) and have an interface (in the languages where they exists).

This way you can:

  • make instances for testing
  • inherit it if necessary (open for extension)
  • can build mockups/stubs for proper testing

Making a singleton has its own problems, but the biggest issues arrive when you are using the instance directly, as a global static instance. This will create hard dependencies, spaghetti code, impossible to test and extend code.

In JS you can avoid these issues by making them as module dependencies, and keep the singleton instance inside a module, at init. But when required, you can inject a mock/stub/replacement in other modules. The best examples are the Window/Nodejs environments that are used as examples in the modules.

PS: is good to have one single instance of an entity (ex: configs, database connections and so on), but do not use them directly, send them as parameters to functions/modules (injection).

tomekbuszewski profile image
Tomek Buszewski Author

I haven't used singletons in a while, but I remember it being quite useful when I was building services for sensitive DOM manipulation and listening. You create a listener in a constructor and this guarantee that this is the only one available. But, like I said, this can be done in a myriad of other ways and I have written this strictly as an informative post.

coly010 profile image
Colum Ferry

Angular uses Singletons a lot. They provide a TypeScript decorator called: @Injectable which turns whichever class is decorated into a Singleton.

The use-case in Angular is logic services. Sure you can use them to maintain state in your App but it can be messy, bug-prone and hairy if you do not take great care in doing so.
However, on the flip side, if you have a class whose function is to provide pure methods or to fetch data from a data-source, then why should you need multiple instances of this class.

In fact, having multiple instances will take up memory within your app. This could be dangerous!
If you do maintain state in your service, perhaps you want to know the loggedInUser, having a singleton for this makes perfect sense. You should only have one logged in user and therefore your singleton will only ever return this one user.

dance2die profile image
Sung M. Kim

If I may, I'd like to shamelessly plug my post about another valid usage of Singleton pattern 😛

The gist is that, Singleton pattern works great in combination with a Null pattern (where the null object is implemented as a singleton).