JavaScript Singleton Pattern: Complete Guide

A complete guide to the JavaScript singleton pattern. Covers closure-based singletons, lazy initialization, module-scope singletons, thread safety considerations, singleton registries, dependency injection alternatives, and anti-pattern awareness.

JavaScriptadvanced
16 min read

The singleton pattern ensures a class or module has only one instance and provides a global access point to it. In JavaScript, singletons manage shared state like configuration, database connections, and caches.

For practical use cases and trade-offs, see When to Use the Singleton Pattern in JS Apps.

Closure-Based Singleton

javascriptjavascript
const Database = (function () {
  let instance = null;
 
  function createInstance(config) {
    // Private state
    const connections = new Map();
    let isConnected = false;
 
    return {
      connect(connectionString) {
        if (isConnected) {
          console.log("Already connected");
          return this;
        }
        console.log(`Connecting to: ${connectionString}`);
        isConnected = true;
        return this;
      },
 
      query(sql, params = []) {
        if (!isConnected) throw new Error("Not connected");
        console.log(`Executing: ${sql}`, params);
        return { rows: [], rowCount: 0 };
      },
 
      disconnect() {
        isConnected = false;
        connections.clear();
        console.log("Disconnected");
      },
 
      isConnected() {
        return isConnected;
      },
    };
  }
 
  return {
    getInstance(config) {
      if (!instance) {
        instance = createInstance(config);
      }
      return instance;
    },
 
    resetInstance() {
      if (instance) {
        instance.disconnect();
        instance = null;
      }
    },
  };
})();
 
// Always returns the same instance
const db1 = Database.getInstance({ host: "localhost" });
const db2 = Database.getInstance({ host: "remote" }); // Config ignored
console.log(db1 === db2); // true

Class-Based Singleton

javascriptjavascript
class Logger {
  static #instance = null;
  #logs = [];
  #level = "info";
  #transports = [];
 
  constructor() {
    if (Logger.#instance) {
      return Logger.#instance;
    }
    Logger.#instance = this;
  }
 
  static getInstance() {
    if (!Logger.#instance) {
      Logger.#instance = new Logger();
    }
    return Logger.#instance;
  }
 
  setLevel(level) {
    const levels = ["debug", "info", "warn", "error"];
    if (!levels.includes(level)) {
      throw new Error(`Invalid level: ${level}. Use: ${levels.join(", ")}`);
    }
    this.#level = level;
    return this;
  }
 
  addTransport(transport) {
    this.#transports.push(transport);
    return this;
  }
 
  #shouldLog(level) {
    const levels = ["debug", "info", "warn", "error"];
    return levels.indexOf(level) >= levels.indexOf(this.#level);
  }
 
  #formatMessage(level, message, meta) {
    return {
      timestamp: new Date().toISOString(),
      level,
      message,
      meta,
    };
  }
 
  #write(entry) {
    this.#logs.push(entry);
 
    for (const transport of this.#transports) {
      transport(entry);
    }
  }
 
  debug(message, meta) {
    if (this.#shouldLog("debug")) {
      this.#write(this.#formatMessage("debug", message, meta));
    }
  }
 
  info(message, meta) {
    if (this.#shouldLog("info")) {
      this.#write(this.#formatMessage("info", message, meta));
    }
  }
 
  warn(message, meta) {
    if (this.#shouldLog("warn")) {
      this.#write(this.#formatMessage("warn", message, meta));
    }
  }
 
  error(message, meta) {
    if (this.#shouldLog("error")) {
      this.#write(this.#formatMessage("error", message, meta));
    }
  }
 
  getLogs(filter) {
    if (!filter) return [...this.#logs];
    return this.#logs.filter((log) =>
      filter.level ? log.level === filter.level : true
    );
  }
 
  clear() {
    this.#logs = [];
  }
 
  static resetInstance() {
    Logger.#instance = null;
  }
}
 
// Usage
const logger1 = Logger.getInstance();
const logger2 = Logger.getInstance();
console.log(logger1 === logger2); // true
 
logger1.setLevel("debug").addTransport(console.log);
logger1.info("Application started");

Module-Scope Singleton (ES Modules)

javascriptjavascript
// config.js - ES modules are naturally singletons
// The module is evaluated once and cached
 
let config = null;
 
function loadConfig() {
  if (config) return config;
 
  config = Object.freeze({
    app: {
      name: "MyApp",
      version: "2.0.0",
      env: process.env.NODE_ENV || "development",
    },
    server: {
      port: parseInt(process.env.PORT) || 3000,
      host: process.env.HOST || "0.0.0.0",
    },
    database: {
      url: process.env.DATABASE_URL || "postgres://localhost/myapp",
      pool: { min: 2, max: 10 },
    },
    cache: {
      ttl: 3600,
      maxSize: 1000,
    },
  });
 
  return config;
}
 
export function getConfig() {
  return loadConfig();
}
 
export function get(path) {
  const parts = path.split(".");
  let current = loadConfig();
  for (const part of parts) {
    if (current === undefined) return undefined;
    current = current[part];
  }
  return current;
}
 
// Every import gets the same config instance:
// import { getConfig } from "./config.js";
// const cfg1 = getConfig();
// const cfg2 = getConfig();
// cfg1 === cfg2 -> true

Lazy Singleton with Proxy

javascriptjavascript
function createLazySingleton(factory) {
  let instance = null;
  let initialized = false;
 
  return new Proxy({}, {
    get(target, prop) {
      if (!initialized) {
        instance = factory();
        initialized = true;
      }
 
      const value = instance[prop];
      return typeof value === "function" ? value.bind(instance) : value;
    },
 
    set(target, prop, value) {
      if (!initialized) {
        instance = factory();
        initialized = true;
      }
      instance[prop] = value;
      return true;
    },
  });
}
 
// Heavy service is NOT created until first property access
const analyticsService = createLazySingleton(() => {
  console.log("Initializing analytics (expensive)...");
  return {
    events: [],
    track(event, data) {
      this.events.push({ event, data, timestamp: Date.now() });
    },
    flush() {
      const batch = [...this.events];
      this.events = [];
      console.log(`Flushing ${batch.length} events`);
      return batch;
    },
  };
});
 
// No initialization yet
console.log("App started");
 
// First access triggers initialization
analyticsService.track("page_view", { path: "/" });

Singleton Registry

javascriptjavascript
class SingletonRegistry {
  static #instances = new Map();
  static #factories = new Map();
 
  static register(name, factory) {
    if (this.#factories.has(name)) {
      throw new Error(`Singleton "${name}" already registered`);
    }
    this.#factories.set(name, factory);
  }
 
  static get(name) {
    if (this.#instances.has(name)) {
      return this.#instances.get(name);
    }
 
    const factory = this.#factories.get(name);
    if (!factory) {
      throw new Error(`Singleton "${name}" not registered`);
    }
 
    const instance = factory();
    this.#instances.set(name, instance);
    return instance;
  }
 
  static has(name) {
    return this.#factories.has(name);
  }
 
  static reset(name) {
    if (name) {
      this.#instances.delete(name);
    } else {
      this.#instances.clear();
    }
  }
 
  static getRegistered() {
    return [...this.#factories.keys()];
  }
}
 
// Register singletons
SingletonRegistry.register("logger", () => new Logger());
SingletonRegistry.register("cache", () => new Map());
SingletonRegistry.register("eventBus", () => {
  const listeners = new Map();
  return {
    on(event, handler) {
      if (!listeners.has(event)) listeners.set(event, []);
      listeners.get(event).push(handler);
    },
    emit(event, ...args) {
      (listeners.get(event) || []).forEach((h) => h(...args));
    },
  };
});
 
// Retrieve anywhere in the app
const logger = SingletonRegistry.get("logger");
const cache = SingletonRegistry.get("cache");
Singleton ApproachProsConsBest For
Closure-based (IIFE)Truly private stateCannot extendLegacy code
Class with static #instanceClear OOP syntaxSlightly verboseModern class-based apps
ES module scopeSimplest, nativeNo lazy init controlMost cases
Proxy-based lazyDeferred initializationProxy overheadExpensive resources
RegistryCentralized managementExtra abstractionLarge applications
Rune AI

Rune AI

Key Insights

  • ES modules are natural singletons: Module code evaluates once and is cached, making module-level variables the simplest shared state mechanism
  • Private class fields (#) enforce the single-instance guarantee: Static private fields prevent external code from creating additional instances
  • Lazy singletons defer expensive initialization: Proxy-based or getInstance() patterns delay resource creation until first access
  • Singleton registries centralize instance management: A registry pattern organizes multiple singletons with named lookup and reset capabilities
  • Always provide a resetInstance() for testability: Tests need fresh singleton state per test case, so expose a way to clear the cached instance
RunePowered by Rune AI

Frequently Asked Questions

Why is the singleton often called an anti-pattern?

Singleton creates hidden global state that makes testing difficult (tests share state), introduces tight coupling (code depends on a specific instance), and obscures dependencies (not passed through constructors). Dependency injection is preferred because it makes dependencies explicit, supports testing with mocks, and allows different configurations per context.

How do I test code that uses singletons?

Expose a `resetInstance()` method and call it in test setup to get a fresh instance per test. Better yet, accept the singleton as a constructor parameter so tests can pass mock objects. For ES module singletons, use module mocking features in test frameworks like Jest (`jest.mock()`) or vitest (`vi.mock()`).

Are ES modules automatically singletons?

Yes. ES modules are evaluated once and cached by the module loader. Every `import` of the same module returns the same exports object. Module-level variables maintain state across imports. This makes ES modules the simplest singleton implementation in modern JavaScript, requiring no special pattern.

When does a singleton become a problem?

Singletons become problematic when multiple parts of the application modify shared state unpredictably, when tests need isolation but share singleton state, when the singleton grows to manage too many responsibilities, or when you need multiple configurations (like test vs production database connections).

Can a singleton be garbage collected?

In the closure pattern, the instance is held by the closure and cannot be garbage collected unless the closure reference is released. In the class pattern, the static reference prevents GC. To allow cleanup, provide a `destroy()` method that nullifies the instance reference. ES module singletons live for the duration of the page.

Conclusion

The singleton pattern ensures a single shared instance for managing state like configuration, logging, and caching. ES module scope provides the simplest singleton behavior. Class-based singletons with private fields offer the clearest modern syntax. For deciding when singletons are appropriate, see When to Use the Singleton Pattern in JS Apps. For the module pattern foundations, see JavaScript Module Pattern: Advanced Tutorial.