QuestionsJavaScript

Singleton — one instance, shared everywhere

Creational PatternsMediumJavaScript

Implement the Singleton pattern in JavaScript. When is it justified, and why do many consider it an anti-pattern?

What it tests

Recognising that JS gives you singletons almost for free (module caching, object literals) and weighing the shared-global-state downsides.

Approach & answer

Singleton guarantees a class has exactly ONE instance and gives a global access point to it. The signal: a resource that must be shared and coordinated app-wide — a config store, a logger, a connection pool, a single cache. In JavaScript you rarely need the textbook class version because the language already hands you singletons: a plain object literal IS a singleton, and — crucially — ES modules are evaluated ONCE and cached, so `export const store = createStore()` yields the same instance to every importer for free. The classic implementation uses a closure with lazy initialisation: a `getInstance()` that creates the instance on first call and returns the cached one thereafter, so you pay construction cost only if it's used. The interviewer usually wants the CAVEAT too: Singleton is often an anti-pattern because it's global mutable state wearing a design-pattern hat — it introduces hidden coupling (callers depend on it without it appearing in their signatures), makes unit testing hard (you can't easily swap a mock, and state leaks between tests unless you add a reset), and can mask ordering/lifecycle bugs. The modern frontend alternative is dependency injection / passing the instance explicitly (or a React context/provider) so the dependency is visible and mockable. Reach for Singleton when there genuinely must be one authority over a resource; avoid it when it's just a convenient global.

Use this technique when

A single shared authority is required — app config, logger, feature-flag client, connection pool, or one cache; prefer DI/context when you need testability.

Complexity

O(1) construction (once) and O(1) access thereafter.

References

js