All topics
Patternsintermediate

Singleton Pattern

Ensuring only one instance of a particular object or resource ever exists throughout an application's lifetime, with a single global access point.

The Singleton pattern restricts a particular class or module to having exactly one instance, providing a single, well-known global point of access to it, and preventing accidental creation of multiple, potentially inconsistent copies of shared state like a configuration object, a logging service, or a database connection pool. In JavaScript, this pattern is often simpler to implement than in classical OOP languages, because module-level state in an ES module is already inherently singleton-like without any extra effort.

A singleton is like a single company mailroom that every department in the building is required to route their outgoing mail through — no department gets its own private mailroom instance, and everyone shares access to the exact same physical mail cart, whether they realize it or not.

Key Concepts

1
The most idiomatic way to implement a singleton in modern JavaScript is simply exporting an already-created instance directly from a module: since ES modules are evaluated only once and cached for every subsequent import, any object literal or class instance created at the module's top level and exported is automatically shared identically across every file that imports it, with zero extra 'ensure only one instance' logic required — the module system itself guarantees it.
2
For cases specifically using a class where you want to enforce single-instantiation even if someone tries new MyClass() multiple times directly, the pattern typically tracks a static private instance reference inside the class itself, and the constructor checks whether an instance already exists, returning the existing one instead of creating a new one if so.
classnew MyClass()
3
Singletons are somewhat controversial in software design broadly, since they introduce global, shared mutable state that can make testing harder (state persists across tests unless carefully reset) and creates hidden coupling between otherwise-unrelated parts of a codebase that all silently depend on the same shared instance. Interviewers sometimes probe not just how to implement one, but whether you recognize these tradeoffs and can articulate when a singleton is the right call (truly single, shared, cross-cutting resources like a logger or app-wide config) versus when dependency injection or simply passing an instance explicitly would be a healthier design choice.