ReviseAlgo Logo

Design Patterns

Singleton Pattern

Master the Singleton Pattern in JavaScript. Learn to restrict class instantiations to a single shared instance, manage global state, and handle modern modules alternatives.

Last Updated: July 15, 2026 10 min read

1. Introduction

The Singleton Pattern is a design pattern that restricts the instantiation of a class to a single, globally accessible instance. It is commonly used to manage shared resources like database connection pools or global configuration states.

2. Why It Matters

Creating multiple instances of classes that manage shared resources (like opening 50 database connections instead of sharing a single pool) wastes resources. The Singleton pattern ensures that a single instance is shared across the entire application.

3. Real-World Analogy

Think of a City Hall Registrar Office:

  • Standard Class (Custom diary): Every citizen buys and carries a private notebook. They write notes in their notebook, and their entries do not affect other notebooks.
  • Singleton (City Hall Registrar): A single registry book maintained in the City Hall lobby. Anyone who needs to register a birth or marriage goes to this registry book. There is only one registry book in the city, ensuring that all records are consistent.

4. Implementing Singleton

You can implement a Singleton by saving the instance in a static property or closure variable, returning the existing instance if it has already been created:

5. ES Module Singleton

In ES Modules, you can create a Singleton easily by instantiating the class inside the module file and exporting the instantiated object. Sibling scripts share the same exported object because modules are evaluated once and cached:

6. Practical Example

This script demonstrates implementing a thread-safe Singleton to manage global configurations using Object.freeze:

7. Common Mistakes

  • Using Singletons as global variable dumps: Overusing Singletons to store random global variables can couple unrelated modules together, making code difficult to unit test. Use them only to manage shared resources.

8. Quick Quiz

Q1: How do ES Modules (ESM) simplify creating Singletons in JavaScript?

A) By introducing the 'singleton' keyword

B) By evaluating module files once and caching the exported objects in memory

Answer: B — ES Modules evaluate module files once and cache exports. Exporting an instantiated object shares that instance across all importing scripts.

9. Scenario-Based Challenge

The Centralized WebSocket Connection Manager:

An application connects to a live notification feed. If multiple components create new WebSocket connections, the server will quickly become overloaded. Design a WebSocket connection manager using the Singleton pattern to share a single connection.

10. Debugging Exercise

Explain why this test suite fails to isolate state across tests, and how to fix it:

class UserSession {
  static #instance = null;
  currentUser = null;

constructor() { if (UserSession.#instance) return UserSession.#instance; UserSession.#instance = this; } }

// Test A: const sessionA = new UserSession(); sessionA.currentUser = 'Alice';

// Test B: const sessionB = new UserSession(); // Bug: sessionB has user 'Alice' pre-filled from Test A! Why?

View Solution

Diagnosis: The Singleton pattern shares the same class instance across all tests. Mutations made in one test leak into subsequent tests, polluting the test environment.

Fix: Implement a reset method on the Singleton class (available only during testing) or reset class properties before every test runs:

class UserSession {
  static #instance = null;
  currentUser = null;

constructor() { if (UserSession.#instance) return UserSession.#instance; UserSession.#instance = this; }

// Testing reset helper reset() { this.currentUser = null; } }

11. Interview Questions

🟢 Q1: What is the Singleton Pattern, and why is it sometimes described as an anti-pattern?

Answer: The Singleton Pattern restricts a class to a single, globally accessible instance.
It is sometimes described as an anti-pattern because:
Global State: It acts like a global variable, making it difficult to trace data flow.
Testing Challenges: Since the instance is shared, tests can contaminate each other unless the singleton state is reset before every test, making parallel testing difficult.
Hidden Dependencies: It hides dependencies inside modules, violating the Dependency Inversion Principle.

12. Production Considerations

  • Testing Isolation: When writing unit tests for modules that import Singletons, use mock frameworks to isolate tests and prevent state from leaking across tests.