What is the singleton pattern in JavaScript?
The singleton pattern ensures a class or module has only one instance, shared everywhere.
How — create the instance once and return that same instance on every request.
In JS — a simple module export is naturally a singleton, since modules are cached.
Use for shared resources like a config store, logger, or DB connection; overuse creates hidden global state.
// Method 1: Module singleton (simplest, recommended)
// config.js
class Config {
constructor() {
this.settings = { theme: 'dark', lang: 'en' };
}
get(key) { return this.settings[key]; }
set(key, value) { this.settings[key] = value; }
}
export default new Config(); // Same instance everywhere
// Method 2: Class with static instance
class Database {
static #instance = null;
constructor(url) {
if (Database.#instance) return Database.#instance;
this.url = url;
this.connected = false;
Database.#instance = this;
}
connect() {
this.connected = true;
console.log(`Connected to ${this.url}`);
}
static getInstance(url) {
if (!Database.#instance) {
Database.#instance = new Database(url);
}
return Database.#instance;
}
}
const db1 = Database.getInstance('postgres://localhost');
const db2 = Database.getInstance('mysql://localhost'); // Returns same instance!
console.log(db1 === db2); // trueModule singleton: export default new Config() creates one instance — every import gets the same object (modules execute once). Class singleton: private static #instance stores the single instance. getInstance checks if it exists — returns existing or creates new.
Subsequent calls with different arguments return the same instance.
The module singleton (export default new Instance()) is the simplest and most Pythonic answer. The class-based approach with static #instance shows OOP knowledge.
Know that ES modules are naturally singletons. Use cases: config, DB pool, logger.