The Singleton Pattern in 30 Lines of Vanilla JS: One Popup Manager to Rule Them All
Scattered popup instances are a common source of state bugs in front-end applications. A Singleton manager is the smallest, most direct fix, and understanding its static-method gate teaches the global-state mindset that underpins larger state-management libraries.
Opening popups from multiple places in a page often leads to scattered, unmanageable instances when each trigger creates its own object. A 30-line vanilla JavaScript implementation shows how the Singleton pattern solves this by locking a single instance behind a static `getInstance()` method. The first call lazily creates the object; every subsequent call returns that same reference, so a popup list recorded in one place is immediately available everywhere else.
The code walks through the three-step template—store the instance on a static property, check if it exists, and provide a unified access point—while clarifying the distinction between static and instance methods that trips up beginners. Connecting the manager to a DOM button with `getElementById` and `addEventListener` demonstrates how any trigger on the page routes through the same Popup object.
Real projects often need to record and close all popups uniformly. Replacing scattered `new Popup()` calls with a Singleton centralizes that state, eliminating the bug where separate instances cannot find each other's windows.
The article identifies a real beginner pitfall: writing `open` as a static method breaks access to instance state, a mistake that stems from not internalizing the static-vs-instance boundary.
Singleton's testability problem is acknowledged honestly—global state couples the instance to everything, and the article points readers toward dependency injection and module-level singletons as mitigations rather than pretending the pattern has no trade-offs.