Member-only story
Singletons in JavaScript
How to implement them and whether they’re actually useful

A singleton is a function or class which can have only one instance. It’s a design pattern popularised by the “Gang of Four” in their influential Design Patterns. However, the singleton is one of several patterns in the book which have been criticised. Some are regarded as anti-patterns, while others are only useful in particular languages. So, what about singletons? And do they make sense JavaScript?
In this article, we’ll see how to implement singletons in JavaScript, before asking whether or not they’re useful in the language.
Class Singleton
Since Design Patterns focused on C++, we’re used to seeing singletons as classes. Since ES6, we’ve had a class syntax in JavaScript, so a basic implementation of a singleton could look something like this:
class Singleton {
constructor() {
if (!Singleton._instance) {
Singleton._instance = this;
}
return Singleton._instance;
}
}
Function Singleton
If we need backwards-compatibility or prefer functions over classes, we can do this with very small tweaks to the example above.
function Singleton() {
if (!Singleton._instance) {
Singleton._instance = this;
}
return Singleton._instance;
}
Accessing the Instance
Whether we’re using a class or a function, any time we call new Singleton()
, we’ll be referring to the same instance. But this could easily become confusing: it’s not the expected behaviour for the new
keyword.
For that reason, it’s common to provide a getInstance
method on the class or function itself.
Class getInstance
class Singleton {
constructor() {
if (!Singleton._instance) {
Singleton._instance = this;
}
return Singleton._instance;
} static getInstance() {
return this._instance;
}
}
Once we’ve created an instance with new Singleton()
, we can then call Singleton.getInstance()
.