A singleton is a design pattern that restricts a class to a single instance and gives the rest of the program one well-known way to reach it. Typical uses are a configuration object, a logger or a connection manager.
Why it matters
Some resources should exist exactly once, and a singleton enforces that rule. It is also one of the most criticized patterns. Because it behaves like a global variable, it hides dependencies, makes code harder to test (state leaks between tests) and can cause trouble in multi-threaded programs if creation is not synchronized. Many teams instead create one instance at startup and pass it where needed, an approach supported by dependency injection.
Example
class Config {
static #instance;
static get() {
return Config.#instance ??= new Config();
}
}
console.log(Config.get() === Config.get()); // true
Both calls return the same object. In JavaScript, a module that exports one object is often an equivalent singleton.
Common mistakes
- Using a singleton as a convenient global for unrelated data.
- Lazily creating it in multi-threaded code without locking, producing two instances.
- Forgetting to reset its state between unit tests.
Related
Get notified when this term updates
Plus occasional practical tips on uptime and monitoring, nothing else. Unsubscribe anytime.
This page is general information written by our editorial team and updated when documentation changes. Servers and providers differ, so test changes safely first. See our editorial policy and disclaimer.