← JavaScript

Patterns & principles · 3 of 10 · 14 min read

The Singleton pattern

One instance, shared everywhere — why an ES module already is one, and the reasons to be careful about reaching for it.

  • Design patterns

A Singleton is a thing there is exactly one of, reachable from anywhere. A configuration object, a database pool, a logger, an app-wide cache.

The module already is one

// store.js — evaluated exactly once, no matter how many importers
export const store = { items: [] };

export function add(item) {
  store.items.push(item);
}
// a.js
import { store, add } from './store.js';
add('from a');

// b.js
import { store } from './store.js';
console.log(store.items); // ["from a"] — the same object, not a copy

That is the whole pattern, with no getInstance, no null check and no class. CommonJS behaves the same way through its require cache:

// counter.cjs
console.log('evaluated'); // printed once per process
let count = 0;
module.exports = { bump: () => ++count };

// elsewhere
const a = require('./counter.cjs'); // "evaluated"
const b = require('./counter.cjs'); // nothing — served from the cache
console.log(a === b); // true

Writing one explicitly

Sometimes you want construction to be lazy — a database pool should not connect when the file is imported, only when something first asks for it:

let instance = null;

export function getPool() {
  if (instance === null) {
    instance = { connected: true, query: (sql) => `running ${sql}` }; // expensive
  }
  return instance;
}

console.log(getPool() === getPool()); // true — built once

The class form, for when an interviewer asks for it by name:

class Logger {
  static #instance = null;
  #lines = [];

  constructor() {
    if (Logger.#instance) return Logger.#instance; // hand back the existing one
    Logger.#instance = this;
  }

  log(message) { this.#lines.push(message); return this.#lines.length; }
  get count() { return this.#lines.length; }
}

const a = new Logger();
const b = new Logger();
console.log(a === b);   // true — `new` returned the first instance
a.log('hello');
console.log(b.count);   // 1

A constructor returning an object overrides the instance new was about to produce, which is what makes this work. A static factory is clearer about its intent, though:

class Config {
  static #instance = null;
  static get instance() {
    Config.#instance ??= new Config();
    return Config.#instance;
  }
}
console.log(Config.instance === Config.instance); // true
Form Lazy Lines Testable
export const x = {…} no — built at import 1 hard
getThing() with a cached let yes 5 hard
class with static #instance yes 10 hard
A factory the app calls once yes 3 easy

The last row is the one worth noticing, and the rest of this page is about why.

Freezing it

A shared mutable object is a shared mutable problem. If the thing is configuration, freeze it:

export const config = Object.freeze({
  apiUrl: 'https://api.example.com',
  retries: 3,
});

config.retries = 99;         // ignored, or TypeError in strict mode — so, in any module
console.log(config.retries); // 3

Remember that freeze is one level deep:

const settings = Object.freeze({ nested: { debug: false } });
settings.nested.debug = true;
console.log(settings.nested.debug); // true — `nested` was never frozen

What is actually wrong with Singletons

Not performance. Three other things, and an interviewer asking “what is wrong with them?” wants these:

It is a global variable with better manners. Any module can import it and change it, so the dependency is invisible at the call site. Reading a function tells you nothing about what it touches.

// What does this function depend on? You cannot tell without reading its body.
export function createOrder(items) {
  logger.info('creating');      // imported singleton
  return { items, currency: config.currency, id: idGenerator.next() };
}

It makes tests leak into each other. The module is evaluated once per process, so state set by one test is still there in the next:

// test A
store.items.push('from A');

// test B — starts with A's data, and the failure looks unrelated
console.log(store.items.length); // 1, not 0

It cannot be substituted. Swapping the real logger for a fake one in a test means reaching into the module registry, which is why test frameworks all have a module-mocking API in the first place.

The alternative: build one, pass it down

Keep a single instance — that was a legitimate requirement — and stop making it globally reachable. Create it once at the top of the program and pass it in:

// logger.js — a factory, not a singleton
export function createLogger(prefix) {
  const lines = [];
  return {
    log: (message) => lines.push(`[${prefix}] ${message}`),
    get lines() { return [...lines]; },
  };
}

// orders.js — says what it needs
export function createOrders({ logger, config }) {
  return {
    create(items) {
      logger.log('creating');
      return { items, currency: config.currency };
    },
  };
}

// main.js — the one place that decides there is exactly one of each
const logger = createLogger('app');
const orders = createOrders({ logger, config: { currency: 'ARS' } });
console.log(orders.create(['a']).currency); // "ARS"

The dependencies are now in the signature, a test can pass a fake in one line, and there is still exactly one logger — because main.js made one. That is Dependency Inversion applied to a Singleton, and it is the answer that lands best in an interview.

When the singleton is right

  • Genuinely process-wide resources: a connection pool, a metrics client, a feature-flag cache. Creating two is a bug, not an inconvenience.
  • Frozen configuration: immutable, so none of the shared-state objections apply.
  • Small apps and scripts, where the ceremony of wiring dependencies buys nothing.

And the case where it is always wrong: per-user or per-request state on a server. A module is evaluated once per process, so a currentUser in module scope is shared by every concurrent request. That is not a caching bug, it is a data leak.

// Never, on a server:
export let currentUser = null; // request B overwrites what request A set

Common mistakes

Putting it on globalThis

Mistake. globalThis.__app ??= createApp(). Why it fails. It escapes the module system, so bundlers cannot see it, two copies of a library collide on the same key, and nothing can tree-shake it. What to do instead. Export it from a module. The module system is already the registry.

Assuming one instance per browser tab is one instance everywhere

Mistake. Treating a module singleton as a source of truth across tabs or workers. Why it fails. Each tab, each worker and each server process evaluates its own copy. What to do instead. For cross-tab state use BroadcastChannel or storage; for cross-process use the database.

Exporting mutable state when a function would do

Mistake. export let token = null and reassigning it from elsewhere. Why it fails. Importers that destructured it captured the old value, and the ones that did not are now reading a variable with no obvious owner. What to do instead. Export getToken() / setToken(), so there is one place that changes it.

Check yourself

One question from the bank on what you just read. Answering here does not affect your quiz history.

In JavaScript, what already gives you Singleton behaviour almost for free?

Practise Design patterns →

Further reading

Everything above is meant to be enough on its own. These are for when you want the full specification of a detail.

Reaching the end of a lecture marks it as read.