Singletons for Web Developers
You don’t need them… Yeah, you probably don’t need them.

The Singleton, one of four creational design pattern introduced/popularized by the Gang of Four, has been beaten to a bloody pulp over the past few years. Understanding the reasons for the animosity will assist developers in the quest to avoid this and similar anti-patterns. To assist future budding software engineers, I’ve compiled a list of articles and books that explore the subject in ways that I’ve found to be interesting, insightful, or otherwise beneficial. Any feedback is appreciated, enjoy!
Resource Index
JavaScript Design Patterns: Singleton, Rod Dodson, article
Singleton Pattern, many authors, wiki
JavaScript Patterns, ch.7, Stoyan Stefanov, book
Learning JavaScript Design Patterns: A JavaScript and jQuery Developer’s Guide, ch.5, Addy Osmani, book
Root Cause of Singletons, Miško Hevery, article
Singletons are Pathological Liars, Miško Hevery, article
The Singleton pattern in JavaScript: not needed, Axel Rauschmayer, article
JavaScript: global variables vs singletons, Shruti Kapoor, article
Global Variables are Bad, many authors, wiki
Avoid Global Variables, Environment Variables, and Singletons, Michael Safyan, article
What does it mean global namespace would be polluted?, Travis J, Stack Overflow response
Highlights
JavaScript Design Patterns: Singleton
- Singletons “ensure a class only has one instance, and provide a global point of access to it.” Global access, if you haven’t heard, is a bad practice in OO programming. One could attach all Singletons to single containing global variable, reducing the opportunity for variable collisions. Some of these problems can be solved by caching the instance in static property or enclosing it within a closure or self-executing function.
- Singletons can be good for certain services, such as logging or commonly used utility packages (think jQuery: $). Their overuse is a sign of a poorly designed system in need of refactoring. In other words, in JavaScript, there is probably a more elegant solution than the Singleton workarounds.
Singleton Pattern
- Pro: Because the Singleton is only instantiated the first time it is used, not when the application begins running, async operations can be performed before instantiation, enabling customization with current application state or fetched data.
- Con: Singletons significantly impact concurrency models, as a thread cannot interact with a Singleton being accessed by another thread. Consequently, each thread needs to be provided its own Singleton to utilize multi-threaded processing.
- “Singleton is a social disease. Because Singleton is so easy to understand, it is the single pattern that almost anybody who merely thumbed through GoF at the bookstore can remember and explain. That leads to unwarranted exuberance for the pattern among those who can least afford such exuberance.”
JavaScript Patterns, ch.7
- Two JavaScript implementations of the Singleton pattern are explored: Instance in a Static Property and Instance in a Closure.
Learning JavaScript Design Patterns: A JavaScript and jQuery Developer’s Guide, ch.5
- Singletons, unlike static classes, can wait on some asynchronous data before instantiating, then providing a globally available isolated namespace with a single point of access.
- Having too many Singletons may mean that disparate modules are too tightly coupled, in which case the structural logic of the application should be reevaluated.
Root Cause of Singletons
- Implementations must provide a global point of access in order to align with the Singleton pattern, and this has all of the same negative consequences as globally stored state.
- Logging is one of the only acceptable cases for Singleton use, as data is only flowing from application to logger, never the other way around. This ensures other parts of the system operate identically regardless of whether or not the Singleton module is included in the code at run-time. That is to say, the only acceptable Singletons are ones that cannot become dependencies.
Singletons are Pathological Liars
- In this article, a scenario is described in which a developer, new to a company mediating transactions, discovers that there are Singleton dependencies that must be instantiated in order to run certain operations. This makes understanding the codebase more difficult and, if there are Singletons depending on other Singletons, possibly could break essential operations if they are instantiated out of order.
The Singleton pattern in JavaScript: not needed
- You probably don’t need Singletons, as JavaScript “lets you directly create objects (being one of the few programming languages that allow you to do so) and there is no trickery necessary.”
- The following extensions may be added to Singletons implementations based on need/degree of security paranoia: hiding data and prevent copying, editing, or exchanging.
JavaScript: global variables vs singletons
- Global variables are either variables without a containing function or undeclared variables with value assignments.
- Singletons, to qualify as the pattern, must be globally accessible, instantiated lazily, not have a public constructor, persist until program termination, and allow sub-classing. Only use them when you need to enforce an object’s singleness, manage instance state, lazily initialize at run-time, and ensure system-wide access.
Global Variables are Bad
- Globals are bad due as they are available for modification anywhere in the program, lack getting and setting control, couple modules requiring consistent access, pollute the global namespace, and make testing environments inconsistent. Each of these drawbacks has a dedicated section explaining further in the full article
- “Perhaps SingletonsAreEvil, but SingletonsAreBetterThanGlobals. Wouldn’t that mean that GlobalVariablesAreBad is an understatement?”
- There are several alternatives to using global variables, with dependency injection and the Singleton pattern being the most relevant for web development.
- With each additional Singleton added to a piece of software, the more convoluted and complex it becomes. Many of these can add up over time, creating a tar pit of a system that requires many changes over many systems in order to restructure.
- Globals may force a system to categorize functionality in ways that may seem initially intuitive, but later require restructuring.
Avoid Global Variables, Environment Variables, and Singletons
- Reasons to avoid using global variables include the likelihood of unconsidered modification resulting in spooky action at a distance and disruption of multi-threaded processing.
- Environment variables are similar to globals, but they are utilized across multiple processes and process instances; they carry all of the same baggage as globals.
What does it mean “global namespace would be polluted”?
- A pollution to the global namespace caused by the haphazardous assignment of values to variables without properly encapsulating them, making them ineligible for garbage collection after they are no longer useful. This means that assigning variables in the global namespace, if done carelessly, will consume space until later overwritten or the program terminates.
- The module pattern can be used to encapsulate functions such that all of the variables involved in processing are garbage collected after the code block is executed.
Singletons are always sources of coding debt except in the rare case where access or lack thereof would not change performance, such as a logging component.
Cheers!
Jacob
Design Patterns for Web Developers series:
- Creational Patterns, inheritance, and Object Composition
- Singletons for Web Developers
- Constructor Functions for Web Developers
Even if you push slow, don’t stop pushing!