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.
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
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); // trueClass-Based Singleton
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)
// 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 -> trueLazy Singleton with Proxy
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
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 Approach | Pros | Cons | Best For |
|---|---|---|---|
| Closure-based (IIFE) | Truly private state | Cannot extend | Legacy code |
| Class with static #instance | Clear OOP syntax | Slightly verbose | Modern class-based apps |
| ES module scope | Simplest, native | No lazy init control | Most cases |
| Proxy-based lazy | Deferred initialization | Proxy overhead | Expensive resources |
| Registry | Centralized management | Extra abstraction | Large applications |
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
Frequently Asked Questions
Why is the singleton often called an anti-pattern?
How do I test code that uses singletons?
Are ES modules automatically singletons?
When does a singleton become a problem?
Can a singleton be garbage collected?
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.
More in this topic
OffscreenCanvas API in JS for UI Performance
Master the OffscreenCanvas API to offload rendering from the main thread. Covers worker-based 2D and WebGL rendering, animation loops inside workers, bitmap transfer, double buffering, chart rendering pipelines, image processing, and performance measurement strategies.
Advanced Web Workers for High Performance JS
Master Web Workers for truly parallel JavaScript execution. Covers dedicated and shared workers, structured cloning, transferable objects, SharedArrayBuffer with Atomics, worker pools, task scheduling, Comlink RPC patterns, module workers, and performance profiling strategies.
JavaScript Macros and Abstract Code Generation
Master JavaScript code generation techniques for compile-time and runtime metaprogramming. Covers AST manipulation, Babel plugin authorship, tagged template literals as macros, code generation pipelines, source-to-source transformation, compile-time evaluation, and safe eval alternatives.