A JavaScript singleton is an object or class pattern that allows only one shared instance. It is commonly used for configuration, logging, caches, feature flags, and service objects that should not be recreated throughout an application.
Use the singleton pattern carefully. A single shared instance can simplify access, but it can also create global state that makes testing and debugging harder.
Environment: Node.js v20.18.2. After each runnable snippet, the following paragraph states the expected console output (order and values).
Method 1: Create a Singleton Class
class Config {
constructor() {
if (Config.instance) return Config.instance;
this.env = "prod";
Config.instance = this;
}
}
const a = new Config();
const b = new Config();
console.log("singleton-same:", a === b);
console.log("singleton-env:", b.env);You should see 2 lines, in order: singleton-same: true, singleton-env: prod.
The constructor returns the existing instance after the first object is created.
Method 2: Use a Static getInstance Method
class Logger {
static getInstance() {
if (!Logger.instance) {
Logger.instance = new Logger();
}
return Logger.instance;
}
}getInstance() makes singleton access explicit and is easier to recognize in larger codebases.
Method 3: Use a Module Singleton
JavaScript modules are evaluated once per runtime module graph, so exporting one object is often the simplest singleton.
const config = { env: "prod" };
export default config;Every importer receives the same exported object reference.
Method 4: Know When Not to Use a Singleton
Avoid a singleton when each test, request, user, or component needs isolated state. Passing dependencies explicitly is often cleaner than reading shared global state.
Common Questions About JavaScript Singleton
What is a singleton in JavaScript?
A singleton is a pattern where code uses one shared instance instead of creating many separate instances.
Does JavaScript need singleton classes?
Not always. ES modules often provide a simpler singleton through a shared exported object.
What is getInstance in JavaScript?
getInstance() is a common static method name that returns the one shared singleton instance.
Summary
Use the JavaScript singleton pattern when one shared instance is truly needed, such as configuration or logging. A class singleton works, but module-level exports are often simpler in modern JavaScript. Avoid singletons for state that should be isolated per user, request, or test.
