Early previewThis guide is in development. Items tagged verify are still being checked against official docs.
nebx Learn
GitHub
Menu
JS

JavaScript

The language of the web, on the client, the server and the edge.

Paradigm
Multi-paradigm, prototype-based, functional
Typing
Dynamic, weak (TypeScript adds static types)
Memory
Garbage collected
Runs
V8 / SpiderMonkey / JSC engines (JIT)
Concurrency
Single-threaded event loop, workers
Creational pattern

Singleton

Intent

Ensures a class has only one instance and provides a global access point to it.

Problem

Several parts of the app need the same configuration or connection pool, and creating duplicates is wasteful or wrong.

Solution

Make the constructor private and expose a static method that creates the instance once and returns it afterwards.

Real-world analogy

Think of it like this

A country has one official government. Whoever asks for “the government” reaches the same one.

Structure

association / extends implements / depends on
Singleton - instance: Singleton {static}- Singleton()+ getInstance(): Singleton {static} 12 ClientA 3 ClientB

Hover or tap a numbered role to highlight it in the diagram.

  1. 1Singleton — Singleton keeps a private static instance and a private constructor, so nobody else can create it.
  2. 2Singleton — getInstance() creates the instance on the first call and returns the same one afterwards.
  3. 3ClientA — Clients call getInstance() and always receive the same object.

Try it

InteractiveAsk for the config from different clients. Turn the pattern off to see the difference.
0instances created
Clients ask for the config
// calls appear here

Code example

singleton.js
// config.js: an ES module is evaluated once, so its export is a singleton.
class Config {
  #values = new Map([["env", "dev"]]);
  get(key) {
    return this.#values.get(key);
  }
}

export const config = new Config();

// elsewhere: import { config } from "./config.js";

Applicability

Use Singleton when exactly one instance must exist (shared config, a single pool).

Use Singleton when you need stricter control than global variables.

How to implement

  1. Add a private static field for the instance
  2. Declare a public static creation method
  3. Implement lazy initialisation, thread-safe if needed
  4. Make the constructor private
  5. Replace direct construction with calls to the static method

Pros and cons

Pros

  • Guaranteed single instance
  • Lazy initialisation

Cons

  • Violates Single Responsibility (manages its lifetime and does work)
  • Hides dependencies and complicates unit tests
  • Needs care in multithreaded code
  • Often better replaced by a DI container singleton lifetime

Relations with other patterns

Check yourself

Check yourself

All modules must share one in-memory cache instance, created lazily on first use.

Saved in this browser only. Part of Creational patterns (0/5), Hands-on: patterns with live demos (0/5).