JavaScript Course
JavaScript
/
Intermediate

Singleton Pattern

Definition

A software design pattern that restricts the instantiation of a class to a singular, single instance. It guarantees that no matter how many times you try to create the object, you always get the exact same one back.

Explain Like I'm New

A Singleton is like the President of a country. No matter which state asks 'Who is the President?', they all get pointed to the exact same person. You cannot instantiate a 'second' President.

Real World Example

A database connection pool, a global Redux store, or a configuration object. If 10 different files import the Database module, they should all be sharing the exact same connection, not spinning up 10 different connections.

Common Use Cases

  • •Global state management
  • •Shared resource coordination (Loggers, Database connections)

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What is the purpose of a Singleton?

intermediate

  • Why are Singletons sometimes considered an anti-pattern?

advanced

  • How do ES6 Modules behave like Singletons by default?

Flash Cards

Question

Why are they sometimes an anti-pattern?

Click to reveal answer
Answer

Singletons are essentially glorified Global Variables. They make unit testing very difficult because state is shared across tests. If Test 1 modifies the Singleton Database, Test 2 might fail unexpectedly because the Database state bled over.

Question

How do ES6 modules behave like Singletons?

Click to reveal answer
Answer

Node.js and Webpack cache modules after the first time they are imported. If `fileA.js` imports `db.js`, the code runs and exports the object. If `fileB.js` then imports `db.js`, the code does NOT run again; it just receives the exact same cached object reference in memory.